Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a new order of the elements after a drag and drop event in JQuery

I have place my sample at the below location : http://jsbin.com/axegem/1

Here is the scenario. When I drag the divs and drop them on to another place, I need to retrieve the new order of the divs. For example, lets say (with respect to my sample), I dragged and dropped DIV 3 after DIV 6. Now I am trying to get the new order of the divs. For testing, I am alerting their html text in the following code:

$(".draggable").each(function(){
  alert($(this).html());
});

I am expecting the alert order to be: DIV 1, DIV 2, DIV 4, DIV 5, DIV 6, DIV 3, DIV 7, DIV 8, DIV 9. But what I get in the sample is DIV 1, DIV 2, DIV 3, DIV 4, DIV 5, DIV 6, DIV 7, DIV 8, DIV 9.

How can I get the new order of the divs after dropping them in a new location?

like image 864
PushCode Avatar asked Feb 01 '13 15:02

PushCode


2 Answers

I have change a little your code to fit your needs.

I have change to using Sortable functionality, that's because you have used the draggable the only drug not sort elements.

When you use the Sortable it will be easily to get the sorted elements

$(document).ready(function() {
    $('#divOuter2').css("margin","-540px 0 0 400px");
    $('#divOuter3').css("margin","-540px 0 0 800px");

    $(".droppable").sortable({
      update: function( event, ui ) {
        Dropped();
      }
    });



  });



    function Dropped(event, ui){
      $(".draggable").each(function(){
        //var p = $(this).position();
        alert($(this).html());
      });
      refresh();
    }

I have set the DOM element with class .droppable as sortable.

Then on Update Event i am calling your function Dropped

See Example

like image 165
Silagy Avatar answered Oct 02 '22 17:10

Silagy


The problem about draggable is that all it does is move items around in a free space and doesn't concern itself with ordering. Droppable can help, but that's more concerned with figuring out if an object is inside of a container.

Instead of using draggable and droppable, try sortable. It makes things like setting sort order of items incredibly simple. That and you no longer have to worry about it fitting in the proper order either.

Check out this: http://jsbin.com/axegem/6/

like image 32
Eric C Avatar answered Oct 02 '22 15:10

Eric C