Draggable div without jQuery UI

holyredbeard picture holyredbeard · Dec 20, 2011 · Viewed 110.2k times · Source

I'm trying to make a div draggable without using jQuery UI.

However, I'm stuck with the code below. I understand that I should use the mouse position relative to the container div (in which the div will be dragged) and that I should set the div's offset relative to those values.

I just can't figure out how. Any clues?

This is the code that doesn't (of course) work:

var X, Y;

$(this).mousedown(function() {
    $(this).offset({ 
        left: X, 
        top: Y
    });
});

$("#containerDiv").mousemove(function(event) {
    X = event.pageX;
    Y = event.pageY;
});

Answer

Andrew Whitaker picture Andrew Whitaker · Dec 20, 2011

Here's a really simple example that might get you started:

$(document).ready(function() {
    var $dragging = null;

    $(document.body).on("mousemove", function(e) {
        if ($dragging) {
            $dragging.offset({
                top: e.pageY,
                left: e.pageX
            });
        }
    });


    $(document.body).on("mousedown", "div", function (e) {
        $dragging = $(e.target);
    });

    $(document.body).on("mouseup", function (e) {
        $dragging = null;
    });
});

Example: http://jsfiddle.net/Jge9z/

I understand that I shall use the mouse position relative to the container div (in which the div shall be dragged) and that I shall set the divs offset relative to those values.

Not so sure about that. It seems to me that in drag and drop you'd always want to use the offset of the elements relative to the document.

If you mean you want to constrain the dragging to a particular area, that's a more complicated issue (but still doable).