Multiple Drag and Drop with jQuery

Tue, Nov 30, 2010 One-minute read

I took inspiration from David Walsh and updated his Drag and Drop script to be able to handle multiple Drag and Drop sections on one page at the same time. Plus I cleaned it up a bit by adding all the functions to a JavaScript object. As jQuery is my preferred JavaScript library this code is using the jQuery version.

Checkout the demo

/* create object */
function DragNDropList(selector){
  this.list = $(selector);
  this.sortInput = jQuery('#sort_order');

  /* store values */
  this.list.children('li').each(function(){
    var li = jQuery(this);
    li.data('id',li.attr('title')).attr('title','');
  });
  /* sortables */
  var obj = this;
  this.list.sortable({
    opacity: 0.7,
    update: function(){
      obj.submit();
    }
  });
  this.list.disableSelection();
}

/* worker function */
DragNDropList.prototype.submit = function(){
  var sortOrder = [];
  this.list.children('li').each(function(){
    sortOrder.push(jQuery(this).data('id'));
  });
  this.sortInput.val(sortOrder.join(','));
  this.request();
}

DragNDropList.prototype.request = function(){
  var obj = this;
  jQuery.ajax({
    success: function(data){
      $("#status").text('Saved');
    },
    error: function(){
      $('#status').text('Failed to save sort order').show();
    },
    data: 'sort_order=' + obj.sortInput[0].value,
    dataType: 'json',
    type: 'post',
    url: '/site/update'
  });
};

// init drag-n-drop lists
var list1 = new DragNDropList('#list1');
var list2 = new DragNDropList('#list2');