I’m adding support for dragging and dropping rows to jQuery, and as you can probably tell from reading this blog, I’m lazy. I don’t want to reinvent the wheel, so I was not very keen on the idea of trying to implement dragging from scratch. jQuery UI to the rescue! But some quick Googling had me discouraged. I couldn’t find any examples where people had successfully used the draggable and droppable plugins in the manner I wanted. Ugh.
Still, I decided to give it a shot, and low-and-behold, I got it working! The hard part was figuring out some of the options because the jQuery UI documentation is not very helpful. The actual code was quite simple.
CSS:
<style type="text/css"> tr.draggable > td > div.ui-state-default { cursor: move; } .ghost { background-color: Gray; opacity: 0.5; } </style>
Markup:
<table> <tr class="draggable droppable"> <td><div class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-grip-dotted-vertical"/></div></td> <td>Test 1</td> <td>Test 1</td> </tr> <tr class="draggable droppable"> <td><div class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-grip-dotted-vertical"/></div></td> <td>Test 2</td> <td>Test 2</td> </tr> <tr class="draggable droppable"> <td><div class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-grip-dotted-vertical"/></div></td> <td>Test 3</td> <td>Test 3</td> </tr> <tr class="draggable droppable"> <td><div class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-grip-dotted-vertical"/></div></td> <td>Test 4</td> <td>Test 4</td> </tr> </table>
And finally script:
$(".draggable").draggable( { helper: function() { return "<div class='ghost'></div>"; }, start: resizeGhost, revert: 'invalid', handle: 'span' }); function resizeGhost(event, ui) { var helper = ui.helper; var element = $(event.target); helper.width(element.width()); helper.height(element.height()); } $(".droppable").droppable({ hoverClass: 'ui-state-active', drop: function(event, ui) { var target = $(event.target); var draggable = ui.draggable; draggable.insertBefore(target); } });
Note that most of the jQuery UI classes I’ve applied are not required, I just used them to get a nice drag handle.
Great article! Thanks!