Download custom drag and drop script

Demo 1 | Demo 2 | Demo 3

Bookmark and Share

Licensing

This script is distributed under the LGPL open source license.
Commercial licenses are also available. Some of these licenses also includes personal e-mail support for up to 1 year.

Download files

You can download the entire script from this Zip file.

Files included in the package:

  • demo-drag-drop-1.html, demo-drag-drop-2.html and demo-drag-drop-3.html = Demo files
  • js/drag-drop-custom.js = Main Javascript file
  • css/demos.css = CSS file the demos

Introduction

This script gives you the possibility to implement drag and drop features into your script. What you have to do is to create an object of the class DHTMLgoodies_dragDrop and then assign dragable elements and drop zones. Example:



var dragDropObj = new DHTMLgoodies_dragDrop();
dragDropObj.addSource('box1',true);
dragDropObj.addSource('box2',true);
dragDropObj.addSource('box3',true);
dragDropObj.addSource('box4',true);
dragDropObj.addTarget('dropBox','dropItems');
dragDropObj.addTarget('leftColumn','dropItems');
dragDropObj.init();

This script is a part of a suite of tools which will be released as package some time before christmas this year.

Important methods

addSource

Add a dragable element. Arguments to this methods are

  1. id of element and
  2. true|false if the element should slide back into it's original position after drop.
  3. true or false if you want to allow dragging along the x-axis. (Optional, default = true)
  4. true or false if you want to allow dragging along the y-axis. (Optional, default = true)
  5. id(String) of element. This argument is optional. If a value is sent, you will not be able to drag the element outside the boundaries of the element with this id.
  6. Name of function(string). Name of function to call when drag is initiated. Example: "onDragStartFunction"(Only the name).
    The function with this name will be called with these arguments: 1) id of the cloned version of the element, and 2) the id of the original element. This script creates a "copy" of the dragged element. The "copy" is the element you see when drag is in process. Look at the code in demo2 for examples on how to use this argument.

addTarget

Assign action to an element when a dragable item is dropped on it.

  1. id of element and
  2. name of function(example: "dropItems") which would be called when an item is dropped on the drop zone. This function would be called with the following arguments:
    1. id of dragged element
    2. id of the element the item was dropped on.
    3. mouse x coordinate when item was dropped
    4. mouse y coordinate when item was dropped

init

Initializes the script. This method should be called after addSource and addTarget

setSlide

Arguments to this function is boolean true or false, false if you want to cancel the sliding animations and true if you want to enable it.

Update log

  • October, 21st, 2006: New feature: Possible to define custom "on drag start" functions.
  • September, 18th, 2006: New features: 1) Limit movement in either vertical or horizontal direction . 2) Limit drag by parent id.

Comments

valeria
hello, i use this method ,but happened one problem , my right part has lots if divs and every div will have more than one child ,then the postion is not right ,i mean when i want to drag box1 to the dropbox4 ,but the box1 is droped to the dropbox1 not the dropbox4 ,i think it should be the position i use the scroll about the drop box part ! i am very glad to use this method ,but i am sorry ,i need your help now
valeria at 02:00AM, 2011/02/24.
Prabu M Rengachari
Hi,I like this feature of drag and drop objects based on JavaScript and idea behind it.ThanksPrabu
Prabu M Rengachari at 12:12AM, 2011/03/16.
miki57
Hi I am new and noobieHow to save this to mysql data base ?Please help
miki57 at 10:02AM, 2011/04/22.
Jasee
You'll need either an OnRelease function or a function that gets value pairs and pushes to MySQL upon button submit.
Jasee at 04:44PM, 2011/04/26.
Marcos
Hola, Necesito saber como desabiltar un drag una ves que se ha unido con su drop.
Marcos at 12:45PM, 2011/06/13.
barb
i tried this script and it worked great locally but when i uploaded to my website, it does not work, the dragging is not working? Any ideas on what went wrong?
barb at 08:24PM, 2011/07/02.
Paul
Great function! I tried four other snippets on the web before i found yours - works like a charm.Small note: the x and y coordinates being returned are not correct - they lack the scroll offset so can't be compared to the div position. Try this instead of line 638 ... if(referenceToDragDropObject.dragDropTargetArray[no][1])eval(referenceToDragDropObject.dragDropTargetArray[no][1] + '( "' + referenceToDragDropObject.dragDropSourcesArray[referenceToDragDropObject.numericIdToBeDragged][0].id + '","' + referenceToDragDropObject.dragDropTargetArray[no][0].id + '", ' + parseInt(e.clientX) + parseInt(Math.max(document.body.scrollLeft,document.documentElement.scrollLeft)) + ' , ' + parseInt(e.clientY + Math.max(document.body.scrollTop,document.documentElement.scrollTop)) + ')');Also, you might like to share this - to allow the dragged blocks to be sorted with the target (depends on the above correction o course)function findPos(inputObj){ var returnValue = inputObj.offsetTop; while((inputObj = inputObj.offsetParent) != null){ if(inputObj.tagName!='HTML'){ returnValue += inputObj.offsetTop; if(document.all && (inputObj.clientTop != undefined)) returnValue+=inputObj.clientTop; } } return returnValue;}// Custom drop actions for and function dropItems(idOfDraggedItem,targetId,x,y){ var dragged = document.getElementById(idOfDraggedItem); var target = document.getElementById(targetId); var targetDivs = target.getElementsByTagName('div'); if (targetDivs.length == 0) { target.appendChild(dragged); return; } var previousOffset = 9999999; var previousTarget = null; for (var i in targetDivs) { if (findPos(targetDivs[i]) < previousOffset && findPos(targetDivs[i]) > y && targetDivs[i].id != idOfDraggedItem){ previousOffset = findPos(targetDivs[i]); previousTarget = targetDivs[i]; } } if (previousTarget != null) { target.insertBefore(dragged,previousTarget); return; } else { target.appendChild(dragged); }}
Paul at 04:12AM, 2011/07/03.
philippe lavigueur
Is it possible that when the element is drop on the right target that an image or text or dialog box appears. If so, what code you be necessary?My aim is to give immediate feedback at each user's choice.
philippe lavigueur at 07:34PM, 2011/07/21.
Paul
Really great job !

Is there a way to adjust to a grid? I suppose that I could set X and Y mouse drop positions to tens numbers emulating and invisible grid.

Maybe you already think about this, let me know please.
Paul at 07:30PM, 2011/08/08.
cali
hi and thanks for sharing this script :)i have a question is it possible to have a decount of available space free.Then i would start the count from the "boxSizeArray" var to zero dinamicly when the user is putting items in the box.i suppose i doable because the script is counting somewhere the max items per box. but i do not know how, if someone could help me it would be very nice :)cheers
cali at 11:01AM, 2011/09/22.
mohamed
i have a problem when i click on the gradable element it move horizontally to right away from mouse pointer what i do
mohamed at 09:44AM, 2011/09/27.
Thomas
Hi,that's nice work.But I need to move a username to a place. Where I drop it, I need textbox which ask me for a phonenumber. So in the final I would like see at which place which user is with which phonenumber availeble.Is it possible? Is there anybody who has an idea.
Thomas at 03:37PM, 2011/11/08.
paddy
I tried the fix for scroll offset . but is not working for me .any suggestions or tips .the div from which i am dragging or dropping has scroll .
<a href="#comment687">Paul wrote:</a><strong>Great function!</strong> I tried four other snippets on the web before i found yours - works like a charm.Small note: the x and y coordinates being returned are not correct - they lack the scroll offset so can't be compared to the div position. Try this instead of line 638 ... <code> if(referenceToDragDropObject.dragDropTargetArray[no][1])eval(referenceToDragDropObject.dragDropTargetArray[no][1] + '( "' + referenceToDragDropObject.dragDropSourcesArray[referenceToDragDropObject.numericIdToBeDragged][0].id + '","' + referenceToDragDropObject.dragDropTargetArray[no][0].id + '", ' + parseInt(e.clientX) + parseInt(Math.max(document.body.scrollLeft,document.documentElement.scrollLeft)) + ' , ' + parseInt(e.clientY + Math.max(document.body.scrollTop,document.documentElement.scrollTop)) + ')');</code>Also, you might like to share this - to allow the dragged blocks to be sorted with the target (depends on the above correction o course)<code>function findPos(inputObj){ var returnValue = inputObj.offsetTop; while((inputObj = inputObj.offsetParent) != null){ if(inputObj.tagName!='HTML'){ returnValue += inputObj.offsetTop; if(document.all && (inputObj.clientTop != undefined)) returnValue+=inputObj.clientTop; } } return returnValue;}// Custom drop actions for and function dropItems(idOfDraggedItem,targetId,x,y){ var dragged = document.getElementById(idOfDraggedItem); var target = document.getElementById(targetId); var targetDivs = target.getElementsByTagName('div'); if (targetDivs.length == 0) { target.appendChild(dragged); return; } var previousOffset = 9999999; var previousTarget = null; for (var i in targetDivs) { if (findPos(targetDivs[i]) < previousOffset && findPos(targetDivs[i]) > y && targetDivs[i].id != idOfDraggedItem){ previousOffset = findPos(targetDivs[i]); previousTarget = targetDivs[i]; } } if (previousTarget != null) { target.insertBefore(dragged,previousTarget); return; } else { target.appendChild(dragged); }}</code>
paddy at 08:28AM, 2011/12/16.
Tuonela
Paddy,You might need to adjust z-index. Can you give more details about your code? Is your document embedded in an iFrame? Do you have static elements on your page?
Tuonela at 06:37PM, 2011/12/16.
Tuonela
You can use an ajax post to submit the data to an external php script.
<a href="#comment389">miki57 wrote:</a>Hi I am new and noobieHow to save this to mysql data base ?Please help
Tuonela at 06:43PM, 2011/12/16.
paddy
<a href="#comment1199">Tuonela wrote:</a>Paddy,You might need to adjust z-index. Can you give more details about your code? Is your document embedded in an iFrame? Do you have static elements on your page?
Thanks for your concern . you can simulate my scenario by setting height of div capitals to 200px and overflow property 200px . In that way you will encounter scroll to that div . now if you try to drag elemnt which lower down the order there is an offset with the cursor of the dragged elemnt due to scrolltop of div . I need to work out for this condition too . your help really appreciable . in your previous comment you suggested about z-index . how can i use it . there are no positioning styles in my div structure .thanks
paddy at 06:45PM, 2011/12/20.
paddy
Tuonela ,here's what i came up with to fix the offset that was been introduced in cursor and the element when the div was scrolled . at around line no 590 . in __moveDragableElement : function(e)i introduced deduction of div scroll offset by " - document.getElementById("capitals").scrollTop "its quiet a small change but worked for me .tested on IE7 , mozilla 3.6 and chrome .var topPos = (e.clientY - referenceToDragDropObject.mouse_y + referenceToDragDropObject.el_y - document.getElementById("capitals").scrollTop); this is in testing phase . hope it works in our project . Any more suggestions solutions , modification would be of great help . thanks a ton " DHTMLGOODIES "
paddy at 07:34PM, 2011/12/20.
paddy
Hi there ,I need to sort the divs using drag and drop . as per js a element is dropped it slides to bottom of the div . now if i have to change the order of the elements how do i do it using drag and drop .
paddy at 06:27AM, 2011/12/26.
sam
How to find TargetId of droppable element on js file
sam at 03:11PM, 2012/01/17.
Andrew Barker
Found an issue.. After the drag is complete.. or at some point during the chain of events, any other event listeners on the object are being cleared.
Andrew Barker at 06:53PM, 2012/03/03.
Andrew Barker
That's because it becomes a completely different object. What the hell is the point of that? Seriously. What the hell were you thinking?
Andrew Barker at 07:02PM, 2012/03/03.
anticommander
What would I need to modify if I wanted to a URL inside of a dragable element that, when clicked, brings me to that URL? As of right now clicking the URL does nothing unless I right click and say "go to link"Thanks!
anticommander at 05:43PM, 2012/03/12.
Albrey
I want to try and learn
Albrey at 12:22AM, 2012/04/07.
dogbear owner
My brain explode with happy. Thanks you!
dogbear owner at 04:32PM, 2012/04/09.
Rudy Smith
This may not work perfectly in all browsers but it centers the dragable item to the mouse pointer if there are scroll bars on the page.change occurred on line 597 and this only does it for Y as my page didn't scroll left and right. var pt = e.pageY;if (pt === undefined){pt = e.clientY + document.documentElement.clientHeight;} dragObj.style.top =pt - this.offsetTop + 'px'; }I also implemented a working autoscroll feature if anyone is interested in this...
Rudy Smith at 02:27PM, 2012/04/24.
Iman Paryudi
Hi, I tried to put this coding in dojo tab. It works well when I put it only in one tab. If I put it in more than one tabs, only drag and drop located in the earliest tab that will work. For instance if I put this coding into tab 2, 3, 4, then only drag and drop in tab 2 that will work. The others do not work.How can i fix the problem?Below is my code (I put the drag and drop coding only in tab 4/"Some Band"):<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <%--DOJO TAB--%> <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" type="text/javascript" djConfig="parseOnLoad:true"></script> <script type="text/javascript"> /* require necessary classes */ dojo.require('dijit.layout.TabContainer'); dojo.require('dijit.layout.ContentPane'); dojo.require('dijit.form.Button'); /* when all classes have loaded... */ dojo.ready(function() { }); </script> <style type="text/css"> @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css"; @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/layout/ContentPane.css"; @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/layout/TabContainer.css"; </style> <%--DRAG N DROP--%> <title>Demo 1: Drag and drop</title> <link rel="stylesheet" href="css/demos.css" media="screen" type="text/css"> <style type="text/css"> /* CSS for the demo. CSS needed for the scripts are loaded dynamically by the scripts */ #mainContainer{ width:600px; margin:0 auto; margin-top:10px; border:1px double #000; padding:3px; } #leftColumn{ width:300px; float:left; } #rightColumn{ width:200px; float:right; margin:2px; height:450px; } .dragableBox{ width:100px; height:60px; border:1px solid #000; background-color:#FFF; margin-bottom:5px; padding:10px; font-weight:bold; text-align:center; } .dropBox{ width:190px; border:1px solid #000; background-color:#E2EBED; height:200px; overflow:auto; margin-bottom:10px; padding:3px; } .clear{ clear:both; } img{ border:0px; } </style> <script type="text/javascript" src="js/drag-drop-custom.js"></script> </head> <body class="claro"><div style="width:700px;height:600px"> <div dojoType="dijit.layout.TabContainer" id="tabContainer" style="width:100%;height:100%;" tabPosition="top-h"> <div dojoType="dijit.layout.ContentPane" title="Rod Stewart" selected="true"> <p>Roderick David "Rod" Stewart, CBE (born 10 January 1945)[1] is a British singer-songwriter...</p> </div> <div dojoType="dijit.layout.ContentPane" title="Oasis"> <p>Oasis were an English rock band that formed in Manchester in 1991...</p> </div> <div dojoType="dijit.layout.ContentPane" title="ColdPlay" closable="true" onClose="alert('Closing Tab!');"> <p>Coldplay are an English alternative rock band...</p> </div> <div dojoType="dijit.layout.ContentPane" title="SomeBand" preload="true"> <div id="mainContainer"> <h2>DRAG AND DROP - demo 1</h2> <div id="leftColumn"> <div class="dragableBox" id="box1">CAT</div> <div class="dragableBox" id="box2">DOG</div> <div class="dragableBox" id="box3">HORSE</div> <div class="dragableBox" id="box4">TIGER</div> </div> <div id="rightColumn"> <div id="dropBox" class="dropBox"> <p><b>Drop some boxes on me</b></p> <div id="dropContent"></div> </div> <div id="dropBox2" class="dropBox"> <p><b>Drop some boxes on me too</b></p> <div id="dropContent2"></div> </div> </div> <div class="clear"></div> <div class="konaBody"></div> </div> <div id="debug"></div> <script type="text/javascript"> // Custom drop actions for <div id="dropBox"> function dropItems(idOfDraggedItem,targetId,x,y) { var html = document.getElementById('dropContent').innerHTML; if(html.length>0)html = html + '<br>'; html = html + 'Item with id="' + idOfDraggedItem+'" dropped'; document.getElementById('dropContent').innerHTML = html; } // Custom drop actions for <div id="dropBox2"> function dropItems2(idOfDraggedItem,targetId,x,y) { var html = document.getElementById('dropContent2').innerHTML; if(html.length>0)html = html + '<br>'; html = html + 'Item "' + document.getElementById(idOfDraggedItem).innerHTML + '" dropped'; document.getElementById('dropContent2').innerHTML = html; } var dragDropObj = new DHTMLgoodies_dragDrop(); dragDropObj.addSource('box1',true); // Make <div id="box1"> dragable. slide item back into original position after drop dragDropObj.addSource('box2',true); // Make <div id="box2"> dragable. slide item back into original position after drop dragDropObj.addSource('box3',true); // Make <div id="box3"> dragable. slide item back into original position after drop dragDropObj.addSource('box4',true); // Make <div id="box4"> dragable. slide item back into original position after drop dragDropObj.addTarget('dropBox','dropItems'); // Set <div id="dropBox"> as a drop target. Call function dropItems on drop dragDropObj.addTarget('dropBox2','dropItems2'); // Set <div id="dropBox2"> as a drop target. Call function dropItems2 on drop dragDropObj.init(); </script> </div> </div></div> </body></html>
Iman Paryudi at 12:56PM, 2012/04/27.
Krish
HI, Its a great look and nice! Can any one suggest how could i make the dragable form element, at the same time i needs to edit,upload file like video audio, and url Please suggest me, I will be very thankful to all.
Krish at 03:38PM, 2012/06/07.
Joakim
Works great, but when I set a position for the container for the dragable boxes (like leftColumn) with something like#leftColumn{position:relative;top:10px;left:10px;width:300px;}(Or anything with the position:x;)The dragable box now offsets from the cursor at a distance the same as from the upper left corner of the website to the container position.Does anyone know what could be done to solve this problem?
Joakim at 04:15PM, 2012/06/08.
Jose
Hi! do you know how can i make this code in asp.net ->Codebehind? sorry about the english...var dragDropObj = new DHTMLgoodies_dragDrop();dragDropObj.addSource('box1',true); dragDropObj.addSource('box2',true); dragDropObj.addSource('box3',true); dragDropObj.addSource('box4',true); dragDropObj.addTarget('dropBox','dropItems'); dragDropObj.addTarget('leftColumn','dropItems'); dragDropObj.init();
Jose at 09:04PM, 2012/08/08.
Dax
I need some help to delay the onmousedown event with this script. I have elements that have an onclick event associated with them and the onmousedown is overriding them.

What i would like to do is have the drag start after the onmousedown has been held for a full second.

Any help is appreciated.

Thanks.
Dax at 02:51AM, 2013/01/07.
pasquale
I have a tree with lot of indentations. Often I see that when I select an item an try to drag it, the item and the mouse pointer move separately, that is the mouse is not placed on the item.Any hint to solve this problem ?
pasquale at 12:52PM, 2013/01/23.
Nitin Jain
Hello,Thanks for this work,Same thing is not working on iPad,Please help me anyone how can I make run the same functionality on iPad.RegardsNitin Jain
Nitin Jain at 07:36PM, 2013/01/28.
Admin comment
DHTMLGoodies
Nitin Jain wrote: #
Hello,Thanks for this work,Same thing is not working on iPad,Please help me anyone how can I make run the same functionality on iPad.

Regards
Nitin Jain


Hi Nitin,

That script was created a long time ago and doesn't support touch drag events. You can try out the new script at:

http://www.ludojs.com/standalone/drag-drop/index.html

---
Alf
DHTMLGoodies.com
DHTMLGoodies at 02:56PM, 2013/01/30.
Silvan Vella
I used this on Pc and worked very good. But on Ipad is not working. Can someone help me pls
Silvan Vella at 12:35PM, 2014/07/02.
smita
Hi ,I want to know if i want to drop one element at one time and if dropping second element, previous element should be reset(revert back to original div). How it will be possible.Please help me , i am new to this.
smita at 11:03AM, 2016/07/05.

Post your comment

Don't have an avatar? Create one at Gravatar.com.

Unable to save captcha-image.