|
||
DHTMLLib Demos/ Drag and Drop
In this demonstration we show you how to use event bubbling to add drag and drop to absolutely
positioned elements. Before we begin, click and drag the two images to the left. When the mouse goes down
the image is automatically centered below the pointer and the image is brought to the top of the z-index. As you drag,
we reposition the image, and when you release the mouse we reset the original z-index. To get a good feel for the z-index control
drop the different images on top of each other and notice how the book image always falls behind the circle.
Adding drag and drop to this page is very simple.
© 1998 by InsideDHTML.com, LLC. All rights reserved.
![]()
// drag-drop code
// This code adds drag-drop to images using the core library only.
var curEl = null // Track current item.
function doMouseMove() {
// Check if mouse button is down
if ((1 == event.button) && (curEl != null)) {
// Move the element
if (null != curEl) {
newleft=event.clientX + document.body.scrollLeft - (curEl.style.pixelWidth/2)
if (newleft<0) newleft=0
newtop = event.clientY + document.body.scrollTop - (curEl.style.pixelHeight/2)
if (newtop < 0) newtop = 0
curEl.style.pixelTop = newtop
curEl.style.pixelLeft = newleft
event.returnValue = false
}
}
}
function doMouseDown() {
// Store element on mousedown. Called from click handler in code below .
// All images that begin with "drag" in their name and are in a positioned DIV
// are draggable.
if (null!=event.srcElement.name)
if (event.srcElement.name.substring(0,4)=="drag") {
curEl = event.srcElement.offsetParent;
curEl.style._zIndex = curEl.style.zIndex
curEl.style.zIndex = 100
}
}
function doMouseUp() {
if (curEl)
curEl.style.zIndex = curEl.style._zIndex
curEl=null
}
// Process mouse
document.onmousedown = doMouseDown
document.onmousemove = doMouseMove
document.onmouseup = doMouseUp