Archive | March 2010

Drag, Drop, Sort & Delete with jQuery & jQueryUI

In my previous post, I discussed how to add drag, drop, sort and delete functions to your website. However, it utilized the prototype and scriptaculous libraries. I had recently changed my site to only use the jQuery library so I needed a way to do this using jQuery. As with my previous post, I could not find any tutorials or how to’s on how to do this so I figured it out on my own and thought I’d share it with the rest of you.

If you are looking for a prototype and scriptaculous solution, look here: https://robertfrew.wordpress.com/2010/02/06/drag-drop-sort-delete-with-script-aculo-us/

Why would you need such a function? This is useful for things such as photo management. In my case, my users can manage their photo albums by viewing a thumbnail page. From that page, they can re-arrange the position of images by dragging them to the correct position. This utilizes the sortable function of jQueryUI. Upon dropping the thumbnail in it’s desired position, on the users screen, it sorts in the foreground. Behind the scenes, it updates the database and arranges the photos in order correctly. If they wish to delete an image, they can drag it to a trash can icon and drop it. It will then remove it from the thumbnail list, reorder (sort) the positions, and remove the image from the database.

Here is the code I used:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>Sorting Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
 $("#namelist").sortable({
 connectWith: '#deleteArea',
 update: function(event, ui){
 //Run this code whenever an item is dragged and dropped out of this list
 var order = $(this).sortable('serialize');
 $.ajax({
 url: 'processImage.php',
 type: 'POST',
 data: order
 });
 }
 });
 $("#deleteArea").droppable({
 accept: '#namelist > li',
 hoverClass: 'dropAreaHover',
 drop: function(event, ui) {
 deleteImage(ui.draggable,ui.helper);
 },
 activeClass: 'dropAreaHover'
 });
 function deleteImage($draggable,$helper){
 params = 'PID=' + $draggable.attr('id');
 $.ajax({
 url: 'deleteImage.php',
 type: 'POST',
 data: params
 });
 $helper.effect('transfer', { to: '#deleteArea', className: 'ui-effects-transfer' },500);
 $draggable.remove();
 }
});
</script>
<style type="text/css">
li { cursor: move; }

</style>
</head>
<body>
<p>Drag and drop list items to sort them out</p>
<ul id="namelist">
 <li id='i_1'>Image 1</li>
 <li id='i_2'>Image 2</li>
 <li id='i_3'>Image 3</li>
 <li id='i_4'>Image 4</li>
</ul>

<div id="deleteArea">
Drag here to delete.
</div>
</body>
</html>