Movable Objects With jQuery UI

17 Nov 2012

First, create your HTML structure. Just a container div with the elements you want draggable as children elements.

    <div id="elements">
         <div id="firstele" class="ele">ONE</div>
         <div id="secondele" class="ele">TWO</div>
         <div id="thirdele" class="ele">THREE</div>
         <div id="fourthele" class="ele">FOUR</div>
         <div id="fifthele" class="ele">FIVE</div>
    </div>

Next you'll want to give the class that applied to the divs some style, as well as the container.

    #elements {

        width:100px;
        background-color:#ffffff;
        position:absolute;
        top:50px;
        right:50px;

    }

    .ele {
        width:100px;
        height:40px;
        padding:3px;
        text-align:center;
        color:#3e3e3e;
        background-color:#ffffff;
        border:1px solid;
        border-color:#3e3e3e;
        overflow:hidden;

    }

Now it's time to add the functionality using jQuery. You'll want to make sure you've linked to jQuery as well as jQuery UI and jQuery UI stylesheet (feel free to link to a local copy).

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
    <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>   
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" type="text/css">

Here's your jQuery code to make the elements duplicate and drag.

    $('div.ele').draggable({helper: "clone"});
        $('div.ele').bind('dragstop', function(event, ui) {
            $(this).after($(ui.helper).clone().draggable());
    });

What we're doing is first adding the .draggable() method which is a jQuery UI method. This does the heavy lifting for us and adds the functionality easily. However, instead of using it normally, $('div.ele').draggable();, I'm making sure that jQuery is targeting the element's clone. This will ensure that the original elements stay put and only the cloned ones are draggable.

Now that we have a nice little div full of draggable elements, it's time to add the trash bin. First of course, add the HTML and style it a bit. In this case I'll add a pseudo "trash.png", but feel free to add whatever image or just a div with some background color.

<div id="trashbin"><img src="trash.png"/></div>

Now add your jQuery. Start with the ID that of the trash bin div and use the jQuery UI method .droppable() as the .draggable() method was used on the other elements. Add an ui event function that will mean whenever a draggable ui element is dropped on the #trashbin element, it will be removed from the DOM.

    $( "#trashbin" ).droppable({
                drop: function( event, ui ) {
                    $(ui.draggable).remove();  
                    }
    });

That's it. Try using this as a basis for an implementation into your project.