Web development by Gabriele Romanato

Post navigation

jQuery: drag and drop tutorial

Drag and drop is one of the most interesting and requested features of an interactive web application. jQuery provides its support to drag and drop functionalities through the jQuery UI framework. In this post I'll cover the main aspects of drag and drop by also providing some background insights.

How drag and drop works

Drag and drop, as implemented by many JavaScript libraries, is simply a system for keeping track of the mouse movements on the screen. When the mouse pointer enters in the content area of an element, when it moves from that area or when one of its buttons is pressed and released, JavaScript keeps track of each of these states thanks to mouse events, which are all related to the more global Event object.

mouseover, mouseleave, mousemove and mouseup are all mouse events involved in this process. But this is not enough. To make drag and drop work, JavaScript must also keep track of the mouse coordinates on the screen. These coordinates are all calculated along the x and y axes, that is, horizontally and vertically.

But how can an element move from one point of another? This happens thanks to CSS relative and absolute positioning. By adjusting the top (y-axis) and left (x-axis) properties, an element can actually be placed on any position on the screen.

This process can be divided into three steps:

start: an element starts being dragged

drag: an element is dragged

drop: an element is dropped

Each one of these steps corresponds to a different position of the element on the screen. Here's a schema:

Let's see now how we can use drag and drop with jQuery.

Drag and drop with jQuery UI

jQuery UI provides two useful wrapper methods for handling drag and drop: draggable() and droppable(). The former applies to an element that must be dragged, while the latter controls the target element of the dragged element. Suppose that you have something like this:

In this case, the draggable() method applies to the element with ID draggable, while droppable() will handle the element with ID droppable. That's because we want to move the first element into the second one.

We also want to apply some changes during the dragging process, both at the beginning and the end of the process. Here's the code:

The opacity of the parent element is adjusted to 0.5 and then back to 1 again, while the element itself is removed at the end of the dragging process. We've not finished yet, because now we have to handle the target element, that is, the droppable element:

The callback function drop() fires when the draggable element is dropped. In this case, we change the HTML content of the droppable element. You can see a demo below. Check out also the references provided below.