inicio mail me! sindicaci;ón

Drag-and-drop table rows with jQuery

There was a project I was working on where I needed to find a way to drag-and-drop rows of a table, basically resort the table rows. Now there were plenty of scripts for doing this within lists, but not so many for actual tables. The final solution I used was from an unexpected source, Isocra Consulting, who setup a jQuery plugin for this functionality. The library, TableDnD plugin, is fairly small, about 15K and was very easy to setup. The plugin included everything I needed without being too feature rich:

onDragStyle
This is the style that is assigned to the row during drag. There are limitations to the styles that can be
associated with a row (such as you can’t assign a border—well you can, but it won’t be
displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
a map (as used in the jQuery css(...) function).
onDropStyle
This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
to what you can do. Also this replaces the original style, so again consider using onDragClass which
is simply added and then removed on drop.
onDragClass
This class is added for the duration of the drag and then removed when the row is dropped. It is more
flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
stylesheet.
onDrop
Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
and the row that was dropped. You can work out the new order of the rows by using
table.tBodies[0].rows.
onDragStart
Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
table and the row which the user has started to drag.
scrollAmount
This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
FF3 beta)

Below are screenshots of the drag-and-drop before and after. As you can see I applied a yellow style to the row I am actively dragging and when dropped, the row flashes green for a second and the zebra-stripping auto-corrects itself.

   

Leave a Comment