Friday, October 19, 2012

Drag and drop from scratch using JavaScript

An example code to implement drag-ability in to an HTML element from scratch without using JavaScript library.

JavaScript functions to provide drag-ability:
function DDElement(ele, event) {
    addEvent(ele, "mousedown", downHandler, true);
    addEvent(document, "mouseup", upHandler, true);

    if (event.stopPropagation)
        event.stopPropagation();
    else
        event.cancelBubble = true;

    if (event.preventDefault)
        event.preventDefault();
    else
        event.returnValue = false;

    function upHandler(e) {
        e = e || window.event;
        removeEvent(document, "mousemove", moveHandler, true);

        if (e.stopPropagation)
            e.stopPropagation();
        else
            e.cancelBubble = true;
    }

    function downHandler(e) {
        e = e || window.event;
        addEvent(document, "mousemove", moveHandler, true);
    }

    function moveHandler(e) {
        e = e || window.event;

        var pos = getCursorPosition(e);

        ele.style.left = (pos.x - 50) + "px";
        ele.style.top = (pos.y - 5) + "px";

        if (e.stopPropagation)
            e.stopPropagation();
        else
            e.cancelBubble = true;
    }
}

function getCursorPosition(e) {
    e = e || window.event;

    var pos = {x:0, y:0};

    if (e.pageX || e.pageY) {
        pos.x = e.pageX;
        pos.y = e.pageY;
    } else {
        var de = document.documentElement;
        var b = document.body;
        pos.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        pos.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

    return pos;
}
HTML element to provide drag-ability:
Handler
Drag Content
Uses: Calling drag and drop on window load:
window.onload = function () {
     DDElement(document.getElementById('dragndrop'));
};

View Demo


No comments:

Post a Comment