Drag-and-Drop for Javascript

SimpleDrag - a very tiny library

Note: This little library still works great. However, it is getting a bit old. I rarely work in Javascript without using one of the many excellent libraries such as jQuery to deal with browser incompatibilities and such. Having said that, if you're looking for a small, lightweight utility, by all means, give SimpleDrag a try!
-Dave (Jan 1, 2011)

A Quick Example

Click here to see a tiny SimpleDrag example.

How to Use

First, grab simpledrag.js.

Then, include it in your page like so:

<script type="text/javascript" src="simpledrag.js"></script>

Finally, make the HTML element of your choice (such as a <div> tag) draggable by assigning dragDown to its onmousedown event like so:

  <script type="text/javascript">
    // assuming "moveme" is the ID of a tag on the page
    var moveme = document.getElementById("moveme");
    moveme.onmousedown = dragDown;

After assigning dragDown() to the onmousedown event of moveme, everything else is automatic. When the user presses the mouse over the moveme object, the dragDown function is called, the other event handlers are created by dragMakeMoveFunc() and dragMakeStopFunc(). When the user releases the mouse, the onmousemove event handler is removed and the object stops moving. That's it!

If nothing else, SimpleDrag is a compact demonstration of closures and higher-order functions in JavaScript.