How do I make an element draggable in jQuery?

zjm1126 picture zjm1126 · Mar 11, 2010 · Viewed 42.6k times · Source

How do I make an element, e.g. a div, draggable using jQuery?

Answer

user982671 picture user982671 · May 8, 2013

You can do with jquery only, without jquery UI:

function handle_mousedown(e){
    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).offset();
    function handle_dragging(e){
        var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
        var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
        $(my_dragging.elem)
        .offset({top: top, left: left});
    }
    function handle_mouseup(e){
        $('body')
        .off('mousemove', handle_dragging)
        .off('mouseup', handle_mouseup);
    }
    $('body')
    .on('mouseup', handle_mouseup)
    .on('mousemove', handle_dragging);
}
$('#b').mousedown(handle_mousedown);