How to make a drag and drop sorted list with jQuery Sortable

Total
0
Shares

A while ago i wanted to build a functionality where some blocks of html had to be sortable (with drag and drop). After searching a little i found jQuery’s Sortable plugin. With the help of this nice little plugin i could build the functionality i required in no time. I will show you below how to do it if you need to do this yourself.

For start we need jQuery, ui.core and ui.sortable, make sure you download them and include them in the header of your application:

<script src=”jquery-latest.js”></script>
<script src=”ui.core.js”></script>
<script src=”ui.sortable.js”></script>

after that we use this little code snippet to make the magic:

<script>

$(document).ready(function(){

$(“.thelist”).sortable({

cursor: ‘.handle’,

update : function () {

serial=$(‘.thelist’).sortable(‘serialize’,’id’);

$(“#target”).load(“load.php”, { list: serial } );

}

});

});

</script>


In the html we have a div with the class thelist, this is the div that contains the sortable elements, each having a unique id.

<div class=”thelist”>

<div class=”divo” id=”el_1″>Item 1</div>

<div class=”divo” id=”el_2″>Item 2</div>

<div class=”divo” id=”el_3″>Item 3</div>

<div class=”divo” id=”el_4″>Item 4</div>

<div class=”divo” id=”el_5″>Item 5</div>

</div>


After each drag and drop operation in load.php will receive a string with the order of the divs, the result will be something like this:

el[]=3&el[]=4&el[]=5&el[]=2&el[]=1

This data is sent to load.php with POST, beeing contained in the list variable: $_POST[‘list’]

This is only a basic demonstration, you can do much advanced functionality with jQuery Sortable, you just need a little time and a little coffee.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like