BIT-101 [2003-2017]

JavaScript Drag and Drop DOM Elements


File this under “really writing this for myself so I can refer back to it later.”

[php lang=“JavaScript”]window.onload = function() {
var foo,
offsetX,
offsetY;

// so it exists
foo = document.createElement(“div”);
document.body.appendChild(foo);

// so we can see it:
foo.style.width = “100px”;
foo.style.height = “100px”;
foo.style.backgroundColor = “blue”;

// so we can move it where we want:
foo.style.position = “absolute”;

// so it looks like something we should click on
foo.style.cursor = “pointer”;

foo.onmousedown = function(event) {
// where is the mouse in relation to the div?
offsetX = event.clientX – parseInt(foo.style.left || 0);
offsetY = event.clientY – parseInt(foo.style.top || 0);

// add listeners
document.onmousemove = onMouseMove;
document.onmouseup = onMouseUp;

// prevent event propagation
event.preventDefault();
return false;
}

function onMouseMove(event) {
// move the div in relation to the mouse
foo.style.left = event.clientX – offsetX;
foo.style.top = event.clientY – offsetY;
}

function onMouseUp(event) {
// remove listeners
document.onmousemove = null;
document.onmouseup = null;
}
}[/php]

Yeah, I know there are ways to make it more reusable, and probably your favorite library has a better version. blah blah blah. I just wanted to lay out the bare bones functionality so it’s plain to see.

« Previous Post
Next Post »