Drag and Drop Using JavaScript
By AzamSharp
Views: 29108

Introduction:

 

JavaScript is an incredibly powerful scripting language. You can create all sort of cool effects using different features provided by JavaScript. One of the coolest effect 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.

 

<div id="a" class="dragElement"> </div>

 

The class “dragElement” gives the basic look for the element. 

 

Creating the Drop Zone:

 

Drop Zones represents 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:

 

 

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”.

 

// 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.

 

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.

 

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.

 

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.

 

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!

 

Download Sample

By AzamSharp




Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Thanks!
Name: wooncherk
Date: 1/30/2007 12:58:00 AM
Comment:
thank you for this article... it's very helpful...
Subject: Excellent Article
Name: Haissam
Date: 1/30/2007 5:49:08 AM
Comment:
Simply a great article. :)
keep up the good work

Haissam Abdul Malak
Subject: Great Article
Name: Vikram
Date: 1/30/2007 8:18:21 PM
Comment:
One suggestion, Please also post the code thta is working with Modzila and other browser. As browser compatibility is one of the most important thing today in the field of web development
Subject: Good One
Name: Manjunath
Date: 1/31/2007 11:12:30 PM
Comment:
It was very simple and straight forward to understand...good work.
Subject: Superb!!
Name: Ambrish
Date: 3/13/2007 11:05:18 PM
Comment:
It helps me alot. Great article.
Keep it up Dear!!!
Subject: nice
Name: thrilochan
Date: 3/14/2007 6:30:13 AM
Comment:
this is very nice.and more needed
Subject: Mozilla
Name: Ken
Date: 3/14/2007 5:17:13 PM
Comment:
You say the article code works in IE only but with mods would work in Mozilla.

Can you give me an idea of what kind of mods I would need to make or things to be aware of, why you say the code wont work in mozilla -This would definitely point me in the right direction to make it work. Thanks for any help in Advance...
Subject: Grate Article
Name: singh santosh
Date: 3/15/2007 3:56:45 PM
Comment:
Today i read your article nothing to say more then this
Genius work
Thanks
Subject: Its a Good Article
Name: Ajay Chauhan
Date: 3/20/2007 2:31:21 AM
Comment:
yeah, it really proves helpful to me. Simple and great, but could u please also post the browse compatible code.
Subject: a bug when browser scrolling
Name: xiangxiang
Date: 3/22/2007 7:15:34 PM
Comment:
it seems that when scrolling browser,the item position changed,
Maybe I test wrong.do you have this bug ?
Subject: Thanks
Name: Vinod Chandra
Date: 3/28/2007 7:32:33 AM
Comment:
This is really helpful
Thanks you
Subject: Good Example
Name: Manish Soni
Date: 4/3/2007 1:51:51 AM
Comment:
Its a nice example. I also have some small example of .Net. If anybody wants then send me a mail.
Subject: drag & drop Shopping Cart
Name: kamalpreet
Date: 4/20/2007 6:52:23 AM
Comment:
the database is invalid & not accessable.would u help me pleasssssssse
Subject: tooooooooo gud
Name: Anu
Date: 4/26/2007 12:13:18 AM
Comment:
this is sumthng great nd really helpful
Subject: Nice one
Name: Sriram
Date: 4/29/2007 10:33:58 PM
Comment:
Hi friend,

I found a nice article. Thanks for it and keep up the same.
Subject: It is Very Good Article
Name: Sajid Khan
Date: 5/15/2007 1:35:38 AM
Comment:
Greate Job Done hop i found a very important code which help me for my shopyy application
Subject: nice good
Name: Eric
Date: 5/17/2007 6:18:11 AM
Comment:
Nice and good reading article for good work.
Subject: drag and drop
Name: Subhan
Date: 5/25/2007 10:52:41 PM
Comment:
Please send the css where the class

like "DefaultDropZoneColor", drag

element are used.
Subject: Feedback for drag and drop in javascript
Name: Naresh
Date: 5/26/2007 12:05:09 AM
Comment:
It very nice.

Please send me such types of codings or controls on my above email address..

Thank you...
Subject: nice work
Name: aman
Date: 6/5/2007 6:57:05 AM
Comment:
dear Azam, its a nice article. keep it up.
thanks
Aman
Subject: nice
Name: rani
Date: 6/14/2007 10:11:10 AM
Comment:
its very good
Subject: Doubt
Name: kiran
Date: 6/20/2007 2:31:39 AM
Comment:
Hi

It is really good. If you don't mine i had one doubt please clarify that
is in gmail address are added automatically after that i am sending one mail to anybody existing mailid are appear as a autocomplete. I want that functionality please give me idea.

With Hope

Kirna Kumar
9948056879
Subject: Excellent
Name: Nithya
Date: 8/22/2007 6:01:06 AM
Comment:
really Great
Subject: thanks
Name: yogesh
Date: 9/12/2007 5:55:42 AM
Comment:
realy good
Subject: good
Name: vidhya
Date: 9/14/2007 2:05:14 AM
Comment:
it is nice to see but when i tried i does'nt work
Subject: not working
Name: justin
Date: 9/20/2007 3:29:32 PM
Comment:
i got the java script down and the drop zone, but do i put the div tag around my object, my object is picture.
Subject: Thanks
Name: Charl
Date: 10/2/2007 12:46:47 AM
Comment:
very helpful, thanks!
Subject: good one
Name: pae sang
Date: 10/29/2007 9:16:55 PM
Comment:
You are always a good one.
I like your stuffs. Thanks a man.
Subject: thanks a lot
Name: aysha akther
Date: 10/29/2007 9:58:12 PM
Comment:
it is very helpful
Subject: great article
Name: sudhakar
Date: 11/14/2007 9:39:14 PM
Comment:
super article, excellent work done
Subject: RE: Good one
Name: AzamSharp
Date: 11/15/2007 5:35:12 AM
Comment:
Hi Pae Sang, I am glad that you liked the article.
Subject: Thanks
Name: venu
Date: 12/9/2007 11:27:04 PM
Comment:
Hi ,

It is a good article. U have explained it without any muzzy.

Bye
Subject: THX
Name: Steve
Date: 12/10/2007 1:00:47 AM
Comment:

Hello!

Great Example, but how can it works in Firefox? What are the modifications for it?

Best Regards
Steve
Subject: RE: THX
Name: AzamSharp
Date: 12/12/2007 1:02:08 PM
Comment:
Hi Steve, I am glad you liked the sample. Yes, this example works only on IE. Check out the following article which works on both the browsers. http://www.koffeekoder.com/ArticleDetails.aspx?id=236
Subject: Thanks a lot
Name: luhuiya
Date: 2/12/2008 4:17:25 AM
Comment:
I'm from China,Thank you.This is a good example.
Subject: gracias
Name: Katherine
Date: 5/16/2008 8:14:18 AM
Comment:
great article - i'm new to this but i followed most of it - thanks for contributing to my free edcucation!
Subject: can we extend ??
Name: sourabh sinha
Date: 5/23/2008 5:34:42 AM
Comment:
It works with images but, i want to enable drag & drop between a gridview & treeview. Can you help me for that???





Join WebHost4Life.com







Copyright GridViewGuy 2007-2008