How to implement Draggable Objects on your page

1. Add a style definition to your page, which defines the container style for the draggable element:

<style type="text/css">
.drag
 {
   border: 1px solid ccccff;
   background-color: rgb(240, 240, 240);
   position: relative;
   cursor: move;
 }
</style>

Mark any element you wish to be draggable with this CSS class name.

2. Add the following JavaScript to your page:



var _startX = 0;           
var _startY = 0;
var _offsetX = 0;           
var _offsetY = 0;
var _dragElement;           
var _oldZIndex = 0;

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

function OnMouseDown(e)
{
    if (e == null) { e = window.event; }
    var target = e.target != null ? e.target : e.srcElement;
    if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag')
    {
        _startX = e.clientX;
        _startY = e.clientY;
        _offsetX = ExtractNumber(target.style.left);
        _offsetY = ExtractNumber(target.style.top);
        _oldZIndex = target.style.zIndex;
        _dragElement = target;
        document.onmousemove = OnMouseMove;
        document.body.focus();
        document.onselectstart = function () { return false; };
        target.ondragstart = function() { return false; };
        return false;
    }
}

function OnMouseMove(e)
{
    if (e == null) { var e = window.event; }
    _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
    _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
    _dragElement.style.zIndex=1000;

        // insert your code here for anything else you want to do while dragging

}

function OnMouseUp(e)
{
    if (_dragElement != null)
    {
        _dragElement.style.zIndex = _oldZIndex;
        document.onmousemove = null;
        document.onselectstart = null;
        _dragElement.ondragstart = null;
        var ypos = parseInt(_dragElement.style.top);
        
        // insert your code here for when the element is dropped again

        _dragElement = null;
    }
}

function ExtractNumber(value)
{
    var n = parseInt(value);
    return n == null || isNaN(n) ? 0 : n;
}
And that is all there is! Any element with the drag classname will now be dragged and dropped by the cursor.