Draggable div without jQuery UI

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).

Leave a Comment