PROGRAMMING SOLUTIONS

Sunday 2 August 2009

Drag and drop in javascript

Copy-paste the following code at the top of your html file, inside the head tag.


var DragDropHandler = {


// private property.
_oElem : null,


// Attach drag handler to an element, public function
attach : function(oElem) {
oElem.onmousedown = DragDropHandler._dragBegin;

// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();

return oElem;
},


// Begin drag process , private function
_dragBegin : function(e) {
var oElem = DragDropHandler._oElem = this;

if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

e = e ? e : window.event;
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;

oElem.dragBegin(oElem, x, y);

document.onmousemove = DragDropHandler._drag;
document.onmouseup = DragDropHandler._dragEnd;
return false;
},


// Drag (move) element , private function
_drag : function(e) {
var oElem = DragDropHandler._oElem;

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

e = e ? e : window.event;
oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';

oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;

oElem.drag(oElem, x, y);

return false;
},


// Stop drag process , private function
_dragEnd : function() {
var oElem = DragDropHandler._oElem;

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

oElem.dragEnd(oElem, x, y);

document.onmousemove = null;
document.onmouseup = null;
DragDropHandler._oElem = null;
}

}

No comments:

Post a Comment