Knowpapa.com - a developer's blog

Tutorial: Create simple drag and drop with jQuery

The jQuery library adds amazing functionality to Javascript. In this example, we will see how we can create simple drag and drop elements with jQuery.

Step 1. Load the jQuery Library to the header section of your html file

The first step is to download the jQuery library from its official site. Two versions of jQuery are available: the uncompressed version (for development or debugging) or the minified version (for actual production sites). You can choose either of the two.

If you don’t want to download the library, you can use the jQuery library hosted on Google or Microsoft. In that case you only need to add the following lines:

For Using Google jQuery Host:



 

For Using Microsoft jQuery Host:




Step 2 Download the jQuery UI plugin

jQueryUI provides several visual control interactions, widgets, utilities & position plugins. For this example, we will use two interactions called ‘Draggable’ & ‘Droppable’.

To download these two modules, visit the website jqueryui.com and click on the “build custom download”. This feature provides the ability to customize your jQuery UI download by selecting the version and specific modules you need for a given project.

From the custom download page, be sure to include:

a) All the core UI Core elements
b) Draggable interactions.
c) Droppable interactions.

The final html head should look like:

Step 3 The HTML elements

The final head area:

      
      
      
  

The html body :

  
Dump Yard
Car
Lorry
Motor Cycle

Step 4 The Actual jQuery Codde for Drag & Drop Elements

We start with the common jQuery wrapper – document.ready() function:

$(document).ready(function(){  //standard wrapper for jQuery

 $(".movers").draggable({    // makes the items in movers class draggable
                revert: true // revert back to original position when released
        });

 $("#droparea").droppable() ({ // makes the area marked #droparea as droppable
tolerance: 'touch', //trigger ‘completed’ function when dropped
completed: function() {
                        alert('Are you sure you want to dump ?');
                }
});  
});

Conclusion

We created a basic example of how to use drag and drop feature in jQuery. We also saw how you can trigger a function when an item is dropped in the droppable area.

This leaves us with unlimited options on how to take it forward from there. You can trigger a jQuery.post function on drop to interact with database, you ca use AJAX features to reload the results without actually refreshing the entire page. The possibilities from here onwards are endless.