Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / Javascript
Article

Drag and Drop Using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.21/5 (13 votes)
19 Apr 20073 min read 112.5K   3.1K   58   10
The drag and drop functionality provided by the JavaScript

Introduction

JavaScript is an incredibly powerful scripting language. You can create all sorts of cool effects using different features provided by JavaScript. One of the coolest effects is the drag and drop feature. As the name implies, you can drag the items on the screen and drop it anywhere, hence changing the position of the items. Usually the draggable item is dropped in the zone known as the drop zone. In this article I will cover the basics of the drag and drop functionality provided by the JavaScript.

Creating a Drag Element

You can create any HTML element as the drag element. I prefer to use the <DIV> elements since they can contain other HTML elements. In the code below I have created a very simple <DIV> element.

The class dragElement gives the basic look for the element.

Creating the Drop Zone

Drop Zones represent the area in which the draggable element can be dropped. The basic idea behind the drop zone is to give the user certain options where they can drop the item. This way they won't be able to drop the item anywhere on the screen. It is also very important that when the user is in drop zone it should alert the user that you are in the drop zone. This can be done by changing the background color of the drop zone or adding different borders. Let's see how we create the drop zone.

<div id="dZone" style="position:absolute; top:100px; right:200; width:300px; 
    height:300px" class="DefaultDropZoneColor">
        Drop Zone 1
</div>

<div id="dZone2" class="DefaultDropZoneColor" style="position:absolute; 
    top:500px; right:200px; width:300px; height:300px">
        Drop Zone 2
</div>

<div id="dZone3" class="DefaultDropZoneColor" style="position:absolute; 
    top:300;right:100px; width:100px; height:200px">
        Drop Zone 3
</div>

As, you can see in the code the drop zone are just simple DIV elements. Take a look at the screen shot below:

Screenshot - DragAndDrop1.jpg

Drag and Drop Implementation

Now, let's see how you can make the element draggable. The function MakeElementDraggable is fired on the window.onload event. The parameter of the MakeElementDraggable is the element which is to be dragged. In this case the element is a DIV element whose id is "a".

JavaScript
// make the element draggable

window.onload = MakeElementDraggable(document.getElementById("a"));

The function MakeElementDraggable does not call any functions but registers an onmouseodown event handler to the InitiateDrag function.

JavaScript
function InitiateDrag(e)
{
    var evt = e || window.event;
   
    startX = parseInt(evt.clientX);
    startY = parseInt(evt.clientY); 
   
    obj.style.top = parseInt(startY) + 'px';
    obj.style.left = parseInt(startX) + 'px'; 

    document.onmousemove = Drag;
    document.onmouseup = Drop; 
   
    return false;            
}

The InitiateDrag function set's the object's position to the mouse location and registers the onmousemove and onmouseup events. The onmousemove event fires the Drag function.

JavaScript
function Drag(e)
{
    // only drag when the mouse is down
    var dropZoneObject;   
    var evt = e || window.event;
    obj.style.top = evt.clientY + 'px';
    obj.style.left = evt.clientX + 'px';

    // Check if we are in the drop Zone
    if(IsInDropZone(evt))
    {       
        dropZoneObject = evt.srcElement;      
        dropZoneObject.className = 'highlightDropZone';
    }

    else
    { 
        ResetColor();   
    }
}

Inside the Drag function we check that if the drag element is inside the drop zone or not. This is done by the IsInDropZone function which iterates through the dropZone array and finds if the drag element is contained by the drop zone element. The dropZoneArray is declared as a global JavaScript variable.

JavaScript
var dropZoneArray = new Array(5);
dropZoneArray[0] = "dZone";
dropZoneArray[1] = "dZone2";
dropZoneArray[2] = "dZone3";

function IsInDropZone(evt)
{
    var result = false;
    var obj = evt.srcElement;

    // iterate through the array and find it the id exists
    for(i = 0; i < dropZoneArray.length; i++)
    {
        if(obj.id == dropZoneArray[i])
        {
            result = true;
            break;
        }
    }
    return result;
}

Finally, the Drop function is fired when the onmouseup event occurs.

JavaScript
function Drop(e)
{
    var evt = e || window.event;

    // check that if we are in the drop zone
    if(IsInDropZone(evt))    
    {       
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

The element is only dropped when the object is inside the DropZone. We set the document.onmouseup and document.onmousemove to null and hence it ends the drag.

Conclusion

Drag and drop is a handy feature that can be used to make the website more interactive. The code presented in this article works only on IE but with just a few modifications it can work on Mozilla.

I hope you liked the article, happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
QuestionA question Pin
Member 118272809-Jul-15 21:44
Member 118272809-Jul-15 21:44 
GeneralMy vote of 5 Pin
Srohith16-Dec-11 19:22
Srohith16-Dec-11 19:22 
Generalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Pin
sharma sanjeev29-Apr-08 1:25
sharma sanjeev29-Apr-08 1:25 
Generalsubject Pin
sharma sanjeev5-Oct-07 0:41
sharma sanjeev5-Oct-07 0:41 
GeneralFirefox Pin
pinturic23-Apr-07 21:44
pinturic23-Apr-07 21:44 
GeneralRe: Firefox Pin
azamsharp24-Apr-07 4:38
azamsharp24-Apr-07 4:38 
GeneralRe: Firefox Pin
pinturic24-Apr-07 4:46
pinturic24-Apr-07 4:46 
GeneralVery good site Pin
foxsermon23-Apr-07 15:00
foxsermon23-Apr-07 15:00 
GeneralRe: Very good site Pin
azamsharp23-Apr-07 16:22
azamsharp23-Apr-07 16:22 
GeneralLive Animation Available Pin
azamsharp19-Apr-07 11:34
azamsharp19-Apr-07 11:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.