The Obscure Art of Drag and Drop: How to Drag and Drop Objects?

Dragging and dropping objects in a web page is a totally fascinating property and surely impressive. Those who are familiar with WordPress administration panel know for example that in order to activate a widget enough dragging it on the sidebar in the desired position. This obviously renders such an operation very easy and intuitive. In this article, we will learn the basics of this rather complex procedure, which thanks to jQuery turns into kids’ play. Does the idea intrigue you? Let us then explore this article.

jQuery user interfaces, a resource of enormous value

The User Interfaces (UI) are a collection of solid extensions which help resolve pretty common problems. For example we can (through a code line), install a datepicker (those tiny calendars which appear on the forms when we have to insert a date) highly configurable both in form and function: see to believe.

The methods draggable() and droppable() which we are going to analyze in detail are part of this collection.

Before getting started, take a look at the example page. As you can see it’s a page consisting in five elements:

  • A container (on the right) which represents the area in which the items can be dropped.
  • An item which cannot be dragged.
  • A draggable item whose drop in the area on the right is not intercepted.
  • A draggable item (solely on the horizontal axis) whose drop is intercepted.
  • A draggable item which during the dragging becomes opaque, whose drop is intercepted, and once dropped remains “glued” to the container. If you notice the previous item, once dropped, it is intercepted; but subsequently it is still possible to reposition it even outside the container.

What you saw is what we are going to do together. As always we start by setting the html page.

Preparing the page

<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html;  charset=iso-8859-1">
    <script  type="text/javascript">
        $(document).ready(function(){
            // here we are going to write the jQuery code
        });
    </script>
</head>
<body>

</body>
</html>

Now let’s insert in the document body the four elements on the left and the dropping area on the right.

<div  id="container">
    <div id="left_block">
        <div class="un_draggable box">
            <p>UN DRAGGABLE</p>
        </div>
        <div  class="draggable box">
            <p>DRAGGABLE</p>
        </div>
        <div  class="draggable_droppable droppable box">
            <p>DRAGGABLE AND DROPPABLE</p>
        </div>
        <div  class="non_reversible droppable box">
            <p>DRAGGABLE DROPPABLE AND NON REVERSIBLE</p>
        </div>
    </div>
    <div id="right_block">
    </div>
</div>

As you can see, I declare the four elements inside the element #left_block. Please notice the classes applied to each of them; the class box is the one which defines the aspect, while the others will serve to define the properties (we’ll see below) of the dragging.

Now let’s write the CSS in the file screen.css

#container{
    margin: 0 auto;
    width: 960px;
}

#left_block{
    float: left;
}

#right_block{
    float: right;
    width:300px;
    height: 300px;
    border: 10px solid  gray;
}

.box{
    background-color: #00AAFF;
    width:  200px;
    padding: 15px;
    text-align: center;
    margin-bottom:  10px;
}

.hover{
    background-color: #FFFFD4;
}

Besides centering the content inside a container, I position the elements and attribute a minimal style to them.

Soon we’ll see what does the class hover define.

In the header of our document we have still to recall jQuery and the extensions which constitute the user interfaces, contained in the file jquery-ui-1.7.2.custom.min.js.

In addition we will include the style sheet screen.css we previously created.

<link  href="screen.css" rel="stylesheet" type="text/css" />
<script  type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script  type="text/javascript"  src="js/jquery-ui-1.7.2.custom.min.js"></script>

We can take a look at the document which now should appear like this

<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html;  charset=iso-8859-1">
    <link href="screen.css"  rel="stylesheet" type="text/css" />
    <script type="text/javascript"  src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript"  src="js/jquery-ui-1.7.2.custom.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
        });
    </script>
</head>

<body>
<div  id="container">
    <div id="left_block">
        <div class="un_draggable box">
            <p>UN DRAGGABLE</p>
        </div>
        <div class="draggable box">
            <p>draggable</p>
        </div>
        <div class="draggable_droppable draggable box">
            <p>DRAGGABLE AND DROPPABLE</p>
        </div>
        <div class="non_reversible draggable box">
            <p>DRAGGABLE DROPPABLE AND NON REVERSIBLE</p>
        </div>
    </div>
    <div id="right_block">
    </div>
</div>
</body>
</html>

At this point the page should appear like in this example.

Now that we are done with the preparation, let’s move on to the realization of the code to activate the drag and drop function.

How to render an element “droppable”

The first thing to do is render the block on the right an area where it is possible to drop an object using the method droppable().

All the block codes we’re gonna add now, are written inside the main function.

$("#right_block").droppable({
    accept: '.droppable',
    hoverClass: 'hover',
    tolerance: 'fit',
    drop: function(event, ui){
        ui.draggable.find('p').html('dropped!');
    }
});

Let’s see now what does the code mean:

  • in the first line we think of rendering the element with id right_block droppable.
  • Afterwards we pass a series of parameters the first of which is accept. In our case it has been valued with .droppable; which means that it’s gonna be possible to drop uniquely all elements with a droppable class.
  • The second parameter is hoverClass. It defines the CSS class to be applied when the dragged element is found above the drop area. In this case, the hover class we have previously defined and which modifies the background color. Flagging when an element is in usable area for the dropping is a matter of usability.
  • The third parameter is tolerance and defines the circumstance in which an element is to be considered in the drop area. We have four possibilities:
    • fit: when the entire dragged element is inside the drop area.
    • pointer: when the pointer of the mouse is inside the drop area;
    • touch: when the dragged element touches the drop area;
    • intersect:  when at least half of the dragged element is found inside the drop area;
  • Finally, by means of the parameter drop we can define the function to be executed at the moment of the drop. In this function, the parameter we have defined with ui, will become the object which will allow us to manipulate and have access to the dragged element and at last dropped to which you can refer by ui.draggable. We will simply limit ourselves to substitute the script contained in the element.
ui.draggable.find('p').html('dropped!');

The code line above means: in the element just dropped, find the p tag and substitute the content of this tag with the script “dropped!“.

How to render elements draggable?

In order to render an object draggable we don’t have to do anything except for applying the draggable() method which we are about to analyze now. We start then by applying the draggable() method to the element with the class “draggable” (second element) in this way:

$(".draggable").draggable();

If you try your script now, you’ll notice that this element has become draggable and can be positioned everywhere. But nothing happens if you drag it to the drop area, why?

We have established that only the elements having droppable class can be dropped and that’s not the case with this element.

How to render objects draggable on a single axis?

Let’s take into consideration the third element.

$(".draggable_droppable").draggable({
    axis: 'x'
});

We have rendered it draggable and have added the property axis set on x. That means that this element is draggable solely on the horizontal axis. There was no need to assign this setting, l did it for a purely didactic just to show you how easy it is to further personalize the dragging.

If we enter the drop area with this element, we will see the background color change, and if we drop it we notice that the script is modified, as a testimony that the event has been intercepted.

In this case however, if you try to drag an element outside the area, you will become aware that this operation is possible.

But what do we have to do in case we wanted that the dropped element remains somehow tied to the container?

How to drag an element and bind it to the container after the drop?

We apply this property to the last element:

$(".non_reversible").draggable({
    opacity: 0.5,
    revert: 'invalid'
});

We have set the parameter opacity on 0.5. This means that during the dragging, the object will become opaque. Even in this case this property has been used for a pure didactic scope.

But what really interests us is the parameter revert set on invalid. In this way, the element once dropped it will no longer be possible to drag it outside. Another effect of this setting is that, in case the element was dragged and dropped outside the preset area, the latter will reposition itself at the starting point.

Here’s the complete function

$(document).ready(function(){
    $(".draggable").draggable();
    $(".draggable_droppable").draggable({
        axis:  'x'
    });

    $(".non_reversible").draggable({
        opacity: 0.5,
        revert: 'invalid'
     });

    $("#right_block").droppable({
        accept:  '.droppable',
        hoverClass: 'hover',
        tolerance: 'fit',
        drop: function(event, ui){
            ui.draggable.find('p').html('dropped!');
        }
    });
});

Conclusion

In this article we saw the basis of a technique which allows us to add dynamic functionalities that make an impact on our websites. I have used the drag and drop in the administration panel of a website in which, everything that can be deleted, can be dragged into the trash (users, contents, etc), something of the sort.

On the user’s side , a common application is the “shopping cart“; a functionality of which you can see a very refined example made with jQuery and based on the principles we have seen in this article.

How about you, do you use it? Can you give us real examples of how you applied or you could apply this technique?

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: , ,

The Author

Maurizio is married to the triad PHP - MySql - Apache and, not enough, he has a lover called jQuery. He has a blog where he tries to describe in detail all of "his lovers". His real specialty is the realization of large business application, altough he never refuses the commitment of a website.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

5 comments

  1. Nick
  2. Andrey

Trackback e pingback

  1. Tweets that mention The Obscure Art of Drag and Drop: How to Drag and Drop Objects? | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by bkmacdaddy designs and others. bkmacdaddy designs said: The Obscure Art of Drag …
  2. How to order the elements with jQuery (1/2) | Your Inspiration Web
    [...] activate a widget we have to drag it in the sidebar with a drag and drag operation as described …

Leave a Reply

Current day month ye@r *