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.

This entry was posted in JavaScript. Bookmark the permalink.

3 Responses to JavaScript Drag and Drop DOM Elements

  1. Justin Mills says:

    Keith

    I have done very similar code in haxe, for instance you may enjoy this play with Bezier curves, drag the circles and click to recalculate path, uses only div’s no canvas.

    http://divtastic.googlecode.com/hg/deploy/bezier_chain/BezierChain.html

    I have just added a snipit of code for dragging a blue circle, which should illustrate how simple it is to use, it also has code for dragging parent.

    http://haxe.org/com/libs/divtastic?lang=en

    currently DisplayDiv also supports using images or video see the repository examples if your interested, hope to add support for canvas and svg content soon. Currently dragging needs more work to target IE but the hexagon colour picker sort of works in IE8.

  2. Luke says:

    “and probably your favorite library has a better version”…

    jQuery UI: $(‘div’).draggable();

    http://jsfiddle.net/lukempeters/ymR4u/3/

    😉

  3. Jeremy says:

    Tried the code in my browser and it didn’t work. Suggestions? Thanks.

Leave a Reply