Drag and Drop using DHTML - Javascript
From Code Trash
Drag and Drop in javascript
Copied from http://www.javascriptkit.com/howto/drag.shtml
<head> <style> <!-- .drag{position:relative;cursor:hand} --> </style> <script language="JavaScript1.2"> <!-- /*Credit JavaScript Kit www.javascriptkit.com*/ var dragapproved=false var z,x,y function move(){ if (event.button==1&&dragapproved){ z.style.pixelLeft=temp1+event.clientX-x z.style.pixelTop=temp2+event.clientY-y return false } } function drags(){ if (!document.all) return if (event.srcElement.className=="drag"){ dragapproved=true z=event.srcElement temp1=z.style.pixelLeft temp2=z.style.pixelTop x=event.clientX y=event.clientY document.onmousemove=move } } document.onmousedown=drags document.onmouseup=new Function("dragapproved=false") //--> </script> </head>
Dragging image elements
Assuming we have in front of us a page like this:
<html> <head> <!--drag engine code here--> </head> <body> <img src="test.gif"><br> <img src="test2.gif"><br> <b>"Hi there</b> </body> </html>
To apply drag-drop capabilities to the first two images above, do this:
<html> <head> <!--drag engine code here--> </head> <body> <img src="test.gif" class="drag"><br> <img src="test2.gif" class="drag"><br> <h1><b>"Hi there</b></h1> </body> </html>The two images will now move when the mouse drags them.
Dragging text elements What about text elements, you say? Well, the engine handles them just as well:
<html> <body> <img src="test.gif"><br> <img src="test2.gif"><br> <h1><b class="drag">"Hi there</b></h1> </body> </html>
Hi there Notice that the class="drag" declaration is added to the innermost element, the <b> element, and not the <h1> element. Now that elements in a page can be dragged, its time to find a practical reason to do so!