No Frills Javascript Drag 'n' Drop
With a minimal bit of script it's really simple to add drag 'n' drop functionality to any elements.
Abstract
To start with we need an element. This element doesn't have many constraints or requirements apart for the obvious; It's got to be a block element visible and have some diamentions.
Lets assume we have a positioned element 100 px from the top and 100 px from the left. Initially the element only needs to have an event handler attached to the onmousedown event. In this event handler we'll attach to the docuemnts onmousemove event (handles the motion) and the documents onmouseup (drops the element). We also need to store the relative position of the mouse pointer to the elements top/left corner.
When the onmousemove event is trigered the event object has the cordinates of the mouse pointer. Using these values and the prevously stored relative position we can calculate where the element should be placed.
The motion has to be stopped when the onmouseup event is fired. This is simple done by detaching the onmousemove event. And to clean up it need to detach it self.
Making it work
var eFoo;
window.onload = function(){
eFoo = document.getElementById("foo");
eFoo.onmousedown = function(e){
e = e||event;
if( e.layerX ){ eFoo.oOffset = {x:e.layerX, y:e.layerY }; }
else { eFoo.oOffset = {x:e.offsetX, y:e.offsetY }; }
document.onmousemove = drag;
document.onmouseup = drop;
document.onselectstart = function(){ return false; };
}
}
function drop(e){
e=e||event;
document.onmousemove = document.onmouseup = document.onselectstart = null;
}
function drag(e){
e=e||event;
eFoo.style.top = e.clientY - eFoo.oOffset.y + "px";
eFoo.style.left = e.clientX - eFoo.oOffset.x + "px";
}
Try it..
Here's a demo of the script in action