jQuery Drag and Drop

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 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.

View Demo

drag-and-drop

Draggble UI Element

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 draggable() function.

<img src="smile.jpg" id="drag_smile">

jQuery draggable() Function

We are calling 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 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 property on initializing draggable.

$( "#drag_smile" ).draggable({ cursor: "hand" });

Setting property after initialization.

$( "#drag_smile" ).draggable();
$( "#drag_smile" ).draggable("option", "cursor", "hand" );

More Options

  • axis – To set the dragging direction (vertical or horizontal).
  • delay – time taken (in milliseconds) to start dragging from pressing mouse.
  • helper – To allow to create the copy of drag element if needed.
  • revert – To restore the drag element to its original position (possible Values true, valid).
  • revertDuration – The time to revert element position.
  • scroll – To contain scrollable drag-area.

And there are much more options in this widget, which makes drag and drop quite interesting.

Functions

  • enable() – To enable drag.
  • disable() – To disable drag.
  • destroy() – To clear drag.
  • options() – To set drag properties.

Events

  • Create – on create.
  • Start – on start dragging the element after mouse down.
  • Drag – during the drag.
  • Stop – on releasing the mouse from dragging.

View Demodownload

This jQuery code tutorial was published on May 27, 2013.

↑ Back to Top