How to create drag & drop interaction with jQuery

Drag & Drop

One of the more interesting actions in visual interfaces is the ability to drag an object and drop it on a selected target. Pretty much like what we do in real life at the supermarket. Grab a beer – drag to cart – drop it in the cart. But there are attributes in the product that it would be interesting to unveil in an application. For example, when you grab a beer you can feel if it’s cold or not, and when you get to the checkout you pay the price of the bottle, which is a hidden attribute of the bottle. Today we will learn how to create drag & drop using  jQuery and adding hidden attributes to the draggable items.

This is what we will be creating: when you start dragging the box, a block will display additional info about that object. It could be text as well as an image, but in order to make things easy I just added some text. Next, when you drop the item on the target area, a message will be displayed along with other hidden information contained in the object.

Example for drag & drop interaction

Markup structure

We will define a container to prevent dragging the element out of boundaries. Next, the draggable elements and within each element, we will add two blocks of hidden info and finally the number that serves as label.

[html]
<div class="container">

<div class="draggable">
<span>Black is not a color, is simply the absence of light</span>

<small>Drop this to find out if black is a color</small>

<p>1</p>
</div>

<div class="draggable">
<span>You’re a genius!</span>

<small>Drop this number to find out your IQ!</small>

<p>2</p>
</div>

<div class="droppable">
<p>Drop it! <br/>Right here, right now.</p>
</div>

</div>
[/html]

CSS definitions

The css is mostly aesthethics but the interesting bits are these:

[css]

.draggable span,
.draggable small{
display:none;
}

[/css]

We hide the span and small elements so that they will only display at drag and drop. You also need to define certain classes to be applied when certain events are triggered:

[css]

.dragactive{
background-color: #ffcccc;
border: 1px dashed #e5a8a8;
}
.drophover{
background-color: #d5eca6;
border: 1px dotted #c7dd9b;
}
.drophighlight{
background-color: #cae9ec;
border: 1px solid #b9d5d8;
}

[/css]

The .dragactive class will be applied to the target area once you have started dragging an item, whereas .drophover will be applied to the target area once you have roll the item over the target. Finally, .drophighlight will be applied to target when you drop the item inside it.

jQuery UI

Besides the jQuery library, you need to include some scripts from jQuery UI components. You can configure your jQuery UI download including only UI Core and Draggable/Droppable from Interactions. For this example I’m using jQuery 1.3.2 + jQuery UI 1.7.2.

Include the proper scripts at header:

[js]
http://jquery-1.3.2.min.js
http://ui.core.js
http://ui.draggable.js
http://ui.droppable.js
[/js]

Now we will build our script, by defining  an interaction for .draggable class and one for .droppable class. The first hidden object will be revealed on the draggable interaction:

[js]
$(".draggable").draggable({
revert: true,
opacity: .75,
containment: ‘.container’,
cursor: ‘move’,
cursorAt: { top: 35, left: 45 },
helper: function(event) {
return $(‘<div>’ + $(this).children("small").text() + ‘</div>’);
},
drag: function(event, ui) {
$(‘.droppable’).removeClass(‘drophighlight’)
.find(‘p’)
.html(‘Drop it!<br/>Right here, right now.’);
}
});
[/js]

Let’s see each option in detail

[js]revert: true[/js]

will return the object that is being dragged back to its original position. That object is named helper and we will define it later. Next, we set the opacity of the dragged object down to .75

[js]opacity: .75[/js]

The next option defines the boundaries of our app

[js]containment: ‘.container’,[/js]

Now we define a cursor type and its position relative to the dragged item

[js]
cursor: ‘move’,
cursorAt: { top: 35, left: 45 },
[/js]

The helper option is bounded to a function looking for a small element within the current element. If found, it will be displayed when we drag the object. When dropped, it will be reverted to its original position and hidden

[js]

helper: function(event) {
return $(‘<div>’ + $(this).children("small").text() + ‘</div>’);
},

[js]</pre>
Finally, the last option is a function invoked when we start dragging the element. With its help, we will clear the text that might be on the target area after the user dropped an object and remove the .drophighlight class that was applied on that event

[js]

drag: function(event, ui) {
$(‘.droppable’).removeClass(‘drophighlight’)
.find(‘p’)
.html(‘Drop it!<br/>Right here, right now.’);
}

[/js]

The second object will be displayed after we drop it on the target area. Let’s configure its interaction:

[js]

$(".droppable").droppable({
activeClass: ‘dragactive’,
hoverClass: ‘drophover’,
drop: function(event, ui) {
$(this).addClass(‘drophighlight’)
.find(‘p’)
.html(‘<h2>Your result:</h2> <br/> ‘ + ui.draggable.children("span").text() + ‘!’);
}
});

[/js]

The first two options define the classes to be applied during the drag action and when the dragged object is on top of the target. The third option defines a funcion triggered when the object is droppped correctly on the target. It will apply the .drophighlight class to the target area and set a message according to the value stored in the span element of the draggable object.

So that’s pretty much it. You can find more attributes of these interactions on the jQuery documentation for Draggable and Droppable and you can download the example below for close inspection.

19 thoughts on “How to create drag & drop interaction with jQuery”

  1. Nice Article. Can i ask something ? If i would like to have after placing the chosen box in container, remove the box from the place. I added in droppable function something like this: ui.draggable.parent().remove();
    But if i remove this dragged item, the second item will have then issue, if i will not place him correctly in container. This issu willnot happen, if i will not remove, this forst dragged item. Is there a way, how to safely remove these items after placing? Thank You for answer and great article …

  2. ice Article. Can i ask something ? If i would like to have after placing the chosen box in container, remove the box from the place. I added in droppable function something like this: ui.draggable.parent().remove();
    But if i remove this dragged item, the second item will have then issue, if i will not place him correctly in container. This issu willnot happen, if i will not remove, this forst dragged item. Is there a way, how to safely remove these items after placing? Thank You for answer and great article …

  3. Hi there!
    I fell in love with your site in first sight!
    The example is awesome but Google Chrome is dumb… 🙁
    Is there a way to run it on chrome?

    1. Google Chrome is my primarily browser 🙂 The script works perfectly on Chrome. Can you tell me what kind of issues are you experiencing?

  4. using this on a school project. thank you! i did have some customization issues.

    here is my link:
    kevin(take this part out)kwok.com/Help/

    1) I managed to replace teh # in boxes with pictures which is what I wanted. Then I wanted to make it so that when i drag it still shows that image as im dragging. I managed to do this by using a background-image element in the css for the “.excerpt” property in the css file. however this makes it so that it is that same image for every picture i drag. example: if picture1 is grabed picture1 is shown being dragged. but with my current method even when picture2 is grabbed, picture1 is still shown while being dragged even though i want picture2 to be shown being dragged… so confusing sorry.

    2) is there a way to display specific images into the box images are dragged into?

  5. Very good website, like it a lot. The jquery is working now just have to trigger a method in ASP.NET once the item is dragged

  6. Thanks very much for this useful post. I was looking for info because I want to create a drag-n-drop way to make forms. I hope this will help in someway.

Leave a Reply