Quantcast
Channel: upshots » ActionScript 3
Viewing all articles
Browse latest Browse all 10

jQuery (or anything else) basics of dragging

$
0
0

Here’s the most basic implementation of dragging I’m aware of… I’ll present an example usin jQuery, but the same logic can be used in any JS framework, raw JS, or even ActionScript, Java, or any other language or technology that processes similar user events and provided a UI.

Here’s the idea:

On mousedown:
1. record the position of the mouse event (x, y, or both).
2. record the position of the element.
3. bind event handlers to the document’s mousemove and mouseup events.

On mousemove:
1. subtract the position of the mouse event from position of the initialization event, recorded when the drag started (mouse down). these values are your deltas, and represent the total change.
2. add the deltas to the position of the element recorded when the drag started.

On mouseup:
1. remove the event handlers for mousemove and mouseup.

It might be implemented using jQuery like so:

$(someAbsolutelyPositionedElement).on('mousedown', function(e){
    var node = $(this);
    var initialized = {
        event : {
            left : e.pageX,
            top : e.pageY
        },
        element : node.offset()
    };
    var handlers = {
        mousemove : function(e){
            node.css({
                left : ( initialized.element.left - initialized.event.left + e.pageX ) + 'px',
                top : ( initialized.element.top - initialized.event.top + e.pageY ) + 'px'
            });
        },
        mouseup : function(e){
            $(this).off(handlers);   
        }
    };
    $(document).on(handlers);
});

POC: http://jsfiddle.net/moagrius/PKESY/


Viewing all articles
Browse latest Browse all 10

Trending Articles