Latest blog post: 10 Epic Dribblers That You Should Be Following →

Tutorial: How to create a simple drag and drop with jQuery

Let’s face it, creating drag and drop functionality with JavaScript alone is tough. What would have taken me hours with JavaScript now takes me a matter of minutes with jQuery. Drag and drop is so beneficial for a web page because it makes it seem more like a desktop application and we all know that that’s where the internet is headed. So here is a quick tutorial to help you get up and running with jQuery drag and drop.

Click here for a demo of what we’ll be making.

1. Create the HTML elements

To use jQuery drag and drop in it’s basic form, there really isn’t any special markup required. Here is the basic setup that we’ll be using:

        <div id="trash" class="out">
                <span>Trash</span>
        </div>
        <div id="items">
                <div class="item"><span>Item 1</span></div>
                <div class="item"><span>Item 2</span></div>
                <div class="item"><span>Item 3</span></div>
        </div>

And here is some some quick css to get the page looking right.

body {
        font: bold 12px arial;
}
 
span {
        float: left;
        margin-top: 17px;
        text-align: center;
        width: 100%;
}
 
#trash, #items, .item {
        height: 50px;
        width: 50px;
}
 
#trash {
        color: #354e62;
}
 
#items {
       margin-top: 10px;
       width: 100%;
}
 
.item {
        background: #cdcdcd;
        color: #3b3b3b;
        float: left;
        margin-right: 10px;
}
 
.over {
    background-color: #cedae3;
}
 
.out {
    background-color: #a6bcce;
}

So here we are setting up a simple example of a drag and drop scenario. We have a bunch of items and a trash bin. We want to be able to drag those items and drop them on the trash bin and trigger a function. Now let’s get ready to code some jQuery!

2. Download and include jQuery files

Drag and drop functions require both the jQuery library and jQuery UI. The jQuery UI website allows you to only download the parts you need so click on “Build custom download” and be sure to include all the UI Core elements plus Draggable and Droppable interactions. Download your custom jQuery UI file and include both the jQuery 1.4 library and the jQuery UI tools in your head of your document like so:

<head>
      <script type="text/javascript" src="js/jquery1.4.2.js"></script>
      <script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>
      <!-- We'll be writing our jQuery in dragdrop.js -->
      <script type="text/javascript" src="js/dragdrop.js"></script>
</head>

3. Create the draggable elements

So let’s get started coding some jQuery. The first thing we need to do is make the items on the page draggable. This only involves a few lines of code:

$(function() {
        $(".item").draggable();
});

That’s it! Reload the page and checkout your new draggable elements. You’ll probably notice an immediate issue. The draggable elements don’t snap back into place. Instead they simply stay wherever they are dragged to. This can be fixed by enabling the ‘revert’ option:

$(function() {
        $(".item").draggable({
                revert: true
        });
});

That’s a lot better. Now we have some nice draggable elements on our page that snap back into place.

4. Create the droppable element

Now that we have our draggable elements, we need a place to drop them. That’s where jQuery Droppable function comes in. All we have to do is declare the trash div as droppable much like we declared the page items as draggable earlier.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable();
});

Now this alone won’t do much. Let’s go ahead and add an alert when an item is held over the trash can so we know that it’s working.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                over: function() {
                        alert('working!');
                }
        });
});

When you hold your cursor over the trash box while you are dragging an item, you should see ‘working!’ in a javascript popup. We are nearly in business. Let’s improve on the overall functionality just a bit. By using droppable’s ‘over’ and ‘out’ options we can make the Trash can change colors when an item is hovering over it.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                over: function() {
                       $(this).removeClass('out').addClass('over');
                },
                out: function() {
                        $(this).removeClass('over').addClass('out');
                }
        });
});

5. Create a deletion confirmation event

Since we are sending these items to the trash. Let’s make a quick alert that asks the user if they would like to proceed. This can be done by adding a function on to the ‘drop’ option of jQuery’s Droppable function. We also need to remember to change the background color of the trash box back to normal since ‘drop’ skips over the ‘out’ function.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                over: function() {
                       $(this).css('backgroundColor', '#cedae3');
                },
                out: function() {
                        $(this).css('backgroundColor', '#a6bcce');
                },
                drop: function() {
                        var answer = confirm('Permantly delete this item?');
                        $(this).removeClass('over').addClass('out');
                }
        });
});

6. Altering the highlight area

You may notice at this point that the droppable item is only triggered when your cursor actually moves over the droppable element. This may be the functionality you want but I prefer for the box to trigger the ‘over’ event when the actual item intersects with the trash box. This can be changed easily by setting the ‘tolerance’ option in our droppable function.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                tolerance: 'touch',
                over: function() {
                       $(this).removeClass('out').addClass('over');
                },
                out: function() {
                        $(this).removeClass('over').addClass('out');
                },
                drop: function() {
                        var answer = confirm('Permantly delete this item?');
                        $(this).removeClass('over').addClass('out');
                }
        });
});

Conclusion

Using the jQuery library with jQuery UI tools we were able to quickly replicate the drag and drop functionality that is commonly found in a desktop application. While this is a basic example of how you can utilize jQuery’s drag and drop functionality, this can be easily expanded by triggering a jQuery.post function on drop that actually removes the item from the database. Then you could reload the results in the items div, creating a working drag and drop file/item manager. The possibilities for this really are endless.

You can download the full source of the tutorial and checkout a demo here.

Well I hope you enjoyed the tutorial and hope it helps you get started using jQuery drag and drop. Did this help you out? Would you do anything different? Please let me know in the comments section below!

Like what you're reading? Follow me on twitter for more!

19 Responses

  1. Eric says:

    @Nic H Just added it sry!

    [Reply]

  2. Nic H says:

    Thanks!

    It seems like in this particular example (with Trash) you wouldn't want the Item to revert back to its original place. Perhaps adding some css to hide the element on drop would be best. Or a big 90 animate fire gif. That would do the trick :)

    [Reply]

  3. Eric says:

    @nic H well I have actually created a full working version of this where I make an ajax call to delete the item on drop and reload the items area with the new markup, the dragged element never reverts back to where it started since the markup for it no longer exists.

    but the animated gif is a good idea.. that could work too hah

    [Reply]

  4. [...] 2.  Tutorial: How to create a simple drag and drop with jQuery [...]

  5. some_guy says:

    Thank you so much for this. You really made this understandable.

    [Reply]

    November 4th, 2010 at 6:52 pm

    No problem ;)

    [Reply]

    November 4th, 2010 at 6:52 pm

    No problem ;)

    [Reply]

  6. Voldhooker says:

    Thanks Eric – I've been looking for something that was just the basics and you provided it.

    [Reply]

  7. prad says:

    Hi, can you please do me a favour ? Can you please do other type of tutorials if not re-write the jquery documentation… ? Thank you so much for this, you've made this extremely understandable.

    [Reply]

  8. Bharath says:

    is it possible to create a droppable area which accepts external files using jQuery or some other js library..

    Thanks in advance.

    [Reply]

  9. Hi Eric

    I have been implementing this drag and drop script in my web side, It works very well. I also have changed for at get the ids of the elements involve

    But I run into a big problems if I try to create dynamically new elements

    I have search for info about .live function but I cannot make it work, do you know if its possible to change this script to make it work with new elements added with JavaScript or Ajax

    Here I paste the code, I will appreciate a lot your help

    Dragdrop.js

    var lll = '';

    $(function() {

    $('div[id^="itemsub"]').draggable({

    drag: function() {

    lll = $(this).attr("id");

    },

    revert: true

    });

    $('div[id^="trashsub"]').droppable({

    tolerance: 'touch',

    over: function() {

    $(this).css('backgroundColor', '#cedae3');

    },

    out: function() {

    $(this).css('backgroundColor', '#a6bcce');

    },

    drop: function() {

    var answer = confirm('Permantly delete this item? from '+lll+' to'+$(this).attr("id"));

    $(this).css('backgroundColor', '#a6bcce');

    }

    });

    });

    Dragdrop.html

    Drag & Drop with jQuery

    function gethtml(){

    document.getElementById("newt").innerHTML = 'Item 4 '

    }

    Trash

    Trash2

    Trash3

    Item 1

    Item 2

    Item 3

    aaaa

    [Reply]

    April 7th, 2011 at 6:03 pm

    Glad it's working for you. Here is a resource with a working sample of adding drop/drag to dynamically created elements. Let me know if you still cannot get it working.

    http://forum.jquery.com/topic/how-do-i-bind-the-d…

    [Reply]

    April 7th, 2011 at 6:03 pm

    Glad it's working for you. Here is a resource with a working sample of adding drop/drag to dynamically created elements. Let me know if you still cannot get it working.

    http://forum.jquery.com/topic/how-do-i-bind-the-d…

    [Reply]

  10. mcavady says:

    Thanks for this! nice and easy. :)

    [Reply]

  11. Saad says:

    wonderful code. ill be using this much, thank u so much

    [Reply]

  12. Krishna Upadhyay says:

    good understandable code……

    [Reply]

  13. macem says:

    .css() method is very slow use css class instead

    [Reply]

    ericbieller
    June 23rd, 2011 at 5:18 am

    Thanks for the tip. I went ahead and updated the code..

    [Reply]

    ericbieller
    June 23rd, 2011 at 5:18 am

    Thanks for the tip. I went ahead and updated the code..

    [Reply]

  14. John says:

    What about keeping reference to the dragged item? How would I be able to manipulate that DOM element after having successfully been dropped in the trash?

    [Reply]

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

The best way to contact me is through one of the networks on the left or by emailing me at
ericbieller [at] gmail [dot] com.