Drag and Drop

Drag and drop is one of the most common DHTML effects and now it is time for me to explain how this is done.

Position the elements

First you need to know that only positioned elements can be dragged. To position an element you set the position style to absolute or relative. Absolute is used for positioning the element relative to the coordinate system set by the parent element. If the parent element is the BODY tag and you set the left and top style to 0 the element will be placed in the upper left corner of the page. Absolute positioned elements don't take up any space inside the parent.

Relative elements is used for placing the element relative to it's original place. Setting the left and top to 0 (or not setting them) places the element at the same place as if no position style was set (in other word static). One big difference is that relative elements take up the space of their (0,0) position inside the parent.

Define event handlers

The next step is to set up all the event handlers. The order in which a drag happens is this. First the mouse button is pressed down (onmousedown). At this time find out what element was pressed and also find out where the mouse was positioned. If it was a valid element set a global variable.

function moveme_onmousedown() {
	el = getReal(window.event.srcElement);	// Find a valid element
	
	if (el.className == "moveme" || el.className == "handle") {
		if (el.className == "handle") {
			tmp = el.getAttribute("handlefor");
			if (tmp == null) {
				dragobject = null;
				return;
			}
			else
				dragobject = eval(tmp);
		}
		else 
			dragobject = el;
		
		if (checkZIndex) makeOnTop(dragobject);
		
		// Get the offset top of the element this gives a smother start of the drag
		ty = window.event.clientY - getTopPos(dragobject);
		tx = window.event.clientX - getLeftPos(dragobject);
			// getTop* checks for browser version and returns the correct position
		window.event.returnValue = false;
		window.event.cancelBubble = true;
	}
	else {
		dragobject = null;
	}
}

Then the mouse is moved, onmousemove, (actually the onmousemove event fires all the time) and if we have a valid dragobject we just updates the left and right position.

function moveme_onmousemove() {
	if (dragobject) {
		if(window.event.clientX >= 0 && window.event.clientY >= 0) {
			dragobject.style.left = window.event.clientX - tx;
			dragobject.style.top = window.event.clientY - ty;
		}
		window.event.returnValue = false;
		window.event.cancelBubble = true;
	}
}

The final event is the onmouseup. Here we only sets the globalobject to null so that it wont be move any more if the mouse is moved.

function moveme_onmouseup() {
	if(dragobject) {
		dragobject = null;
	}
}

Drag and Drop
Setting up the page
As a behavior

Author: Erik Arvidsson