Try dragging one of the items below:

Item 1 is <div>
Item 2 is <div>
drag image


Because I found no succinct and understandable tutorials on how to implement drag and drop with javascript, I came up with the below.  Credit where credit is due: I used a article to generate this single-page tutorial; the article discusses general drag and drop issues.

Drag and drop is a topic that can be explored to great lengths somewhere else; all you need to know about it here is that you left-click-and-hold on one "draggable element", and then move your mouse with the left button down: the element you clicked on follows your mouse.  Restrictions on what can be dragged and where it can be dragged are discussed briefly.  If you know about a better tutorial on this topic, or have suggestions, please let me know!  Quirksmode now has a drag and drop tutorial, although it is quite a bit longer than this one.  Go there for completness, stay here for succinctness.

Draggable Elements

The following javascript will allow dragging html elements with class="drag".  The only required css is:

.drag { position: relative; }

Global Variables

Quite a few global variables are required to make things possible:

var _startX = 0; // mouse starting positions var _startY = 0; var _offsetX = 0; // current element offset var _offsetY = 0; var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove var _oldZIndex = 0; // we temporarily increase the z-index during drag var _debug = $('debug'); // makes life easier

JavaScript Events

The relevant events belong to the document: onMouseDown, onMouseMove, and onMouseUp.  Attempting to make drag and drop using onMouseMove of an element will result in buggy operation, as the cursor tends to jump outside of the element when it is moved quickly; when this happens, onMouseMove will stop firing until the mouse moves back over the element. Clearly, this is not desirable, so the document's mouse events are used.

Two events are initialized here:

InitDragDrop(); function InitDragDrop() { document.onmousedown = OnMouseDown; document.onmouseup = OnMouseUp; }

We start with onMouseDown:

function OnMouseDown(e) { // IE is retarded and doesn't pass the event object if (e == null) e = window.event; // IE uses srcElement, others use target var target = != null ? : e.srcElement; _debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked'; // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = ExtractNumber(; _offsetY = ExtractNumber(; // bring the clicked element to the front while it is being dragged _oldZIndex =; = 10000; // we need to access the element in OnMouseMove _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; // prevent text selection (except IE) return false; } }

The comments cover just about everything; the "text selection" stuff exists because we want to avoid selecting text when dragging things around.  Once OnMouseMove is wired up, it will fire whenever the mouse moves:

function OnMouseMove(e) { if (e == null) var e = window.event; // this is the actual "drag code" = (_offsetX + e.clientX - _startX) + 'px'; = (_offsetY + e.clientY - _startY) + 'px'; _debug.innerHTML = '(' + + ', ' + + ')'; }

When the mouse is released, we remove the event handlers and reset _dragElement:

function OnMouseUp(e) { if (_dragElement != null) { = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; _debug.innerHTML = 'mouse up'; } }

Utility Functions

function ExtractNumber(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; } // this is simply a shortcut for the eyes and fingers function $(id) { return document.getElementById(id); }

Some Things to Consider

This example only scratches the surface of drag and drop.  For example, dragging is often only initiated if the user clicks and drags the mouse more than a pixel for two (to prevent jitter or something, it's a common practice).  Moreover, one often wants to drag from one place to another, instead of just randomly.  Keep on the lookout for a more advanced drag and drop tutorial covering these sorts of things.  Simplicity first!

Determining what elements one is dragging over is tricky, because the onmouseover event does not fire if the cursor is over the element being dragged.  The only solution [known to the author] is to look for elements under the cursor by position.  position.js from the Prototype javascript library demonstrates the requirements for doing this.  Determining the Droppable provides a nice overview of this process.

The code presented blatantly overwrites any existing event handlers.  If other javascript needs to deal with these events, one should investigate attachEvent, or more generally, event handling in Javascript.

<iframe />

I have not tested this, but apparently event.screenX and event.screenY should be used instead of clientX and clientY if one is using iframes.

Mouse Buttons

Because browser makers love incompatibility, the codes for event.button vary from browser to browser; see the below table for values and feel free to provide me with additional rows for other browsers.

BrowserLeft ClickMiddle ClickRight Click
Internet Explorer142

Note that IE uses the values 1, 2, and 4 so that one can determine every mouse button that is pressed; Firefox does not allow this.

Browser compatibility

This example has only been tested in IE6&7, Firefox 3.0.5, Opera 9.2+, and Chrome 2.0; results from testing in other browsers would be appreciated.

Support Tutorials like This

If you found this tutorial helpful, please link to it.  If you really want to show your appreciation... :-)