Drag and Drop Example using jQuery JavaScript in HTML

Introduction:
Using jQuery you can create simple Drag & Drop features easily and manage them well. jQuery UI provides with a vast suite of APIs that can be leveraged to create a UI with Drag Drop functionality.

The jQuery UI Droppable plugin makes selected elements droppable (meaning they accept being dropped on by draggables). You can specify which (individually) or which kind of draggables each will accept.

Include jQuery
First include the jQuery library in your code where you want to add drag/drop functionality.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" 
type="text/javascript"> </script>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"
 type="text/javascript"> </script>

Code Snippet

$("#draggable").draggable();
$("#droppable").droppable ({
    drop: function() { alert('dropped'); }
});

The full code HTML

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" 
type="text/javascript"> </script>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"
 type="text/javascript"> </script>

</head>
<body>
<div id="move" style="background-color: pink; border: 1px solid #999999; 
height: 150px; width: 150px;"> </div>
<script>$(document).ready(function(){$("#move").draggable();});</script>
</body>
</html>

$("#draggable").draggable();
The above code makes an element with ID draggable, draggable. So that means you don’t have to write cross browser javascript to do these things.

Also note that we have called a function .droppable which makes an item to react when you drop any draggable item on it.


Callback Functions

We can provide different callback functions which gets called on different events such as start, stop, drag. These callback functions has two arguements, first is the browser event object and second is the ui object that represents:
* ui.helper – the jQuery object representing the helper that’s being dragged
* ui.position – current position of the helper as { top, left } object, relative to the offset element
* ui.offset – current absolute position of the helper as { top, left } object, relative to page



DEMO:
Drag the following box.
--------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------
Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment