Drag and drop to change position of elements

Long time ago, I was trying to figure out how to change position of items in a list. Let’s say there’s a list of product in an e-commerce solution and the user wants to choose what items go first and what go last. What I used back then was to create a simple form which called a function that takes the id of the previous or next item and swaps it for the current item’s id and vice versa. It was simple, but it worked. But now I needed something more user-friendly, after all it’s true that this solution was not very convenient for long lists. This is where the motto of jQuery “write less, do more” comes handy.

See demo here.

First, you need a table containing the items:

item 1
item 2
item 3
item 4
item 5
item 6

Now download jQuery and the Table Drag and Drop plugin (if you are new to jQuery, there’s great documentation on their page).

Having installed jQuery file and the TableDnD plugin, we need to get things working. Include this in the head section of the website:

$(document).ready(function() {
		onDrop: function(table, row) {
		var ordered_items = $.tableDnD.serialize('id');
	        $('#result').load("save_new_positions.php?" + ordered_items);

$(“#positions”).tableDnD() tells jQuery to apply the TableDnD plugin on the table with id positions. As simple as it can ever get. You can try to drag and drop items here

The last thing is to save the new positions to the database.

onDrop: function(table, row) – this says that once you drop an item, something else happens

var ordered_items = $.tableDnD.serialize(‘id’); – this puts all the items to an array (in the newly selected order)

Now we use an AJAX function .load()

$(‘#result’).load(“save_new_positions.php?” + ordered_items); – this tells jQuery to load whatever result we get form an external file save_new_positions.php to a div with id result. We also pass the ordered items array to the php file in the form of an url parameter.

The last thing we need is the above mentioned save_new_positions.php that will save the new positioning in the database.

$positions = $_GET["positions"];
echo 'saved in order: ';
foreach ($positions as $key=>$option) {
		echo $option . ', ';
		// this is where you can put your SQL query, maybe something like
		// $query = 'UPDATE table SET position = '.$key.' WHERE id = '.$option.' LIMIT 1';
		// mysql_query($query) or die (mysql_error());

That’s all, you can see the demo here. and you can find much more in the post this post was based on.

Leave a Reply