Javascript Drag-and-Drop

Posted in Javascript on September 14, 2008

0


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.
 

Write a comment