www.hutsky.cz / blog / twitter /

Posts Tagged ‘ajax’

Drag and drop to change position of elements

Wednesday, June 2nd, 2010

Long time ago, I was trying to figure out how to change position of items in a list. Let’s say there’s a list of product in an e-commerce solution and the user wants to choose what items go first and what go last. What I used back then was to create a simple form which called a function that takes the id of the previous or next item and swaps it for the current item’s id and vice versa. It was simple, but it worked. But now I needed something more user-friendly, after all it’s true that this solution was not very convenient for long lists. This is where the motto of jQuery “write less, do more” comes handy.

See demo here.

First, you need a table containing the items:

  1. <table id="positions">
  2.           <tr id="1"><td>item 1</td></tr>
  3.           <tr id="2"><td>item 2</td></tr>
  4.           <tr id="3"><td>item 3</td></tr>
  5.           <tr id="4"><td>item 4</td></tr>
  6.           <tr id="5"><td>item 5</td></tr>
  7.           <tr id="6"><td>item 6</td></tr>
  8. </table>

Now download jQuery and the Table Drag and Drop plugin (if you are new to jQuery, there’s great documentation on their page).

Having installed jQuery file and the TableDnD plugin, we need to get things working. Include this in the head section of the website:

(more…)