
In this tutorial, we are going see an example code for jQuery drag and drop. In this example, we need jquery UI library to use drag and drop functions.
We are using a draggable() function to move a draggable element. This function is call with the reference of the selector string denoting HTML element to be drag and drop.
This is the image element to be dragged by using jQuery. We are referring this image by an id. This id selector is used in jQuery to call the draggable() function.
<img src="smile.jpg" id="drag_smile">
We are calling the draggable() function with respect to the id of the image element. Using this single line script we can drag and drop the element anywhere in the window.
$( "#drag_smile" ).draggable();
If we want to limit the drag area, then we have to use this code.
$(function() { $( "#drag_smile" ).draggable({ containment: "parent" }); });
There are more options, methods, and events to control jQuery drag and drop. The drag and drop options can be set as the arguments of draggable().
For example, we are setting cursor property to the drag event. These two methods can be used while setting drag properties.
Setting a property on initializing draggable.
$( "#drag_smile" ).draggable({ cursor: "hand" });
Setting property after initialization.
$( "#drag_smile" ).draggable(); $( "#drag_smile" ).draggable("option", "cursor", "hand" );
And there are much more options in this widget, which makes drag and drop quite interesting.
View Demo download