Programming Rambling

mrzard's ramblings in the wild

Drag and Drop Interaction Made Easy With jQuery (and jQuery UI)

| Comments

Last week at work I had to make a drag-and-drop configurable homepage, where individual news items had to had the ability to be moved and arranged in a grid which represented the available placeholders on the homepage.

My work was made MUCH easier by the draggable and droppable plugins in jQuery UI. I just had to add a class which I binded the draggable plugin to to the news items and then add another class to the placeholders which I binded to the droppable plugin.

In case it’s of help for somebody, here’s a quick ‘skeleton’ on top of which you can code the drag&drop interactions you want.

Draggable-Droppable example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

  var draggable_options = {
          helper: 'clone',  /* makes the item 'move' a copy of itself rather than 
                         '   leave' the original area */
          revert: 'invalid',    /* makes the item return to its original position 
                             if not dropped in a 'droppable' area */
          cursor: 'move'       // changes the cursor appearance on hover 
  };

  //we give the items the draggable plugin with the options 
  $(".draggable").draggable(draggable_options);

  $(".droppable").droppable({
      drop: function(event, ui) {
          /* detect where we dropped the draggable element, 
         in my case, the key part was the element's id */
          var dropped_in = $(this).attr('id');
          
          /* here i put '...' in the droppable container's body to inform 
         the user 'something' is happening */
          var context = $(this);
          context.html('...');
          
          var dragged = $(ui.draggable);
          /* ui.draggable is a reference to the dropped element. 
         Now you can use all jQuery functions like dragged.attr('id') to get its id, 
         or dragged.html('whatever') to change its innerHTML, etc... */

          /* Here comes interaction, the removal of '...' and 
         display of the action results */
      }
  });

Comments