Javascript Drag-and-Drop

September 14th, 2008 Leave a comment Go to comments

I spent a lot of time trying to find a simple, lightweight, drag-and-drop example to learn from.  Finally I located a drag-and-drop demo from the fine folks at WebToolkit.  The Javascript is only 50 lines which impressed even me.  I've tested this to work with Firefox, IE, and Opera.

Here's how to use it.  The element must have position:absolute; or position:relative;.
var dragable = dragHandler.attach(document.getElementById('some_element_id'));
/*This function will be called when dragging starts.  Note that we do not write begin(); here. */
dragable.dragBegin = begin;
/*This function will be called every time the element moves.*/
dragable.drag = drag;
/*This function will be called when dragging ends.*/
dragable.dragEnd = end;
The last three lines are optional.  You can write your own functions (here, imaginitively named 'begin', 'drag', and 'end') that will be run when you specify.

Here's a Drag-and-Drop example I made.  Check the source code for the rest of the Javascript.

If you would like a reply to your comment, you must leave your email address! We receive dozens of questions every month from people who don't leave us with any way to contact them, so we have no choice but to ignore the question. We try to reply to as many questions as we can, if we know the email address of the person who asked the question. Thanks in advance for writing in :)

Allowed HTML: <b>, <i>, <em>, <strong>. All other < and > will be replaced with &lt; and &gt;.