Drag and Drop using DHTML
A while back, a demonstration of an element being dragged
around in a browser during a computer show finally convinced web developers
that DHTML was not just another version of JavaScript, but something more.
In this tutorial, we will demonstrate how to implement onto
your web page drag-drop capabilities in IE 4.x; this is not a tutorial on
how to program your own drag-drop capabilities, but rather, how to install a
pre-made script that enables drag drop.
Installing the
drag-drop engine
We've designed and created the drag-drop engine to make it
as easy to use as possible. The below is the engine, and should be inserted
in the <head> section of your page:
<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>
Once the engine has been installed, enabling any
element in a page to be dragable is a snap. Simply give the element a
class="drag"
declaration.
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! |