JavaScript Drag and Drop Tutorial
(last updated: 21.02.09 00:19 UTC)Try dragging one of the items below:
![drag image](http://luke.breuer.com/tutorial/drag_image.png)
NON-draggable element clicked
Introduction
由于没有太好的关于如何用javascript实现拖拽
Because I found no succinct and understandable tutorials on how to implementdrag and drop with javascript, I came up with the below. Credit where is due:I used a devarticles.com article to generate this single-page tutorial; the article discussesgeneral drag and drop issues.
Drag and drop is a topic that can be explored to great lengths somewhere else; allyou 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 followsyour mouse. Restrictions on what can be dragged and where it can be dragged arediscussed briefly. If you know about a better tutorial on this topic, or have suggestions, please let me know! Quirksmode now hasa drag and drop tutorial, althoughit 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 positionsvar _startY = 0;var _offsetX = 0; // current element offsetvar _offsetY = 0;var _dragElement; // needs to be passed from OnMouseDown to OnMouseMovevar _oldZIndex = 0; // we temporarily increase the z-index during dragvar _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 elementwhen it is moved quickly; when this happens, onMouseMove
will stop firing until themouse moves back over the element. Clearly, this is not desirable, so the document's mouse eventsare 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 = e.target != null ? e.target : 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(target.style.left); _offsetY = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 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 existsbecause we want to avoid selecting text when dragging things around. OnceOnMouseMove
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" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; _debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')'; }
When the mouse is released, we remove the event handlers and reset _dragElement
:
function OnMouseUp(e){ if (_dragElement != null) { _dragElement.style.zIndex = _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 fingersfunction $(id){ return document.getElementById(id);}
Some Things to Consider
This example only scratches the surface of drag and drop. For example, dragging isoften 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 wantsto drag from one place to another, instead of just randomly. Keep on the lookoutfor 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.jsfrom the Prototype javascript library demonstratesthe 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 javascriptneeds to deal with these events, one should investigate attachEvent
, or moregenerally, event handling in Javascript.
<iframe />
I have not tested this, but apparently event.screenX
and event.screenY
should be used instead ofclientX
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.
Browser | Left Click | Middle Click | Right Click |
---|---|---|---|
Firefox | 0 | 1 | 2 |
Internet Explorer | 1 | 4 | 2 |
Note that IE uses the values 1, 2, and 4 so that one can determine every mouse buttonthat 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... :-)