Monday, February 23, 2009

Javascript for drag an htmll element

Javascript
function startdrag(t, e) {
if (e.preventDefault) e.preventDefault(); //line for IE compatibility
e.cancelBubble = true;
window.document.onmousemoveOld = window.document.onmousemove;
window.document.onmouseupOld = window.document.onmouseup;
window.document.onmousemove=dodrag;
window.document.onmouseup=stopdrag;
window.document.draged = t;
t.dragX = e.clientX;
t.dragY = e.clientY;
return false;
}

function dodrag(e) {

if (!e) e = event; //line for IE compatibility
t = window.document.draged;
t.style.left = (t.offsetLeft + e.clientX - t.dragX)+"px";
t.style.top = (t.offsetTop + e.clientY - t.dragY)+"px";
t.dragX = e.clientX;
t.dragY = e.clientY;
return false;
}
//restore event-handlers
function stopdrag() {
window.document.onmousemove=window.document.onmousemoveOld;
window.document.onmouseup=window.document.onmouseupOld;
}

HTML
<DIV
style="width:100px;height:100px;background:#EEEEEE;border:1px solid black"
><table style="position:absolute;border-color: black; border-style: solid; border-width: 1px" width="20%" onmousedown="startdrag(this, event);"><tr><td>Darg Me</td></tr></table></DIV>

No comments: