Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out about the "snapped to" element for jQuery UI draggable elements on snap

I'm working a few draggable elements that should be snapping to other elements, which all have classes, something like, ".classes" and also a unique id, "#class_id". Once the draggable elements are done being dragged, I would like to find out which of those ".classes" that the draggable element has snapped to.

I suppose I could compute the closest element based on the current position of the dragged element, but I feel there should be an easier way than brute force, since jQuery would have to keep some sort of variable to make sure the snapping works.

Any suggestions? Thanks!

like image 445
jet Avatar asked Mar 03 '11 07:03

jet


1 Answers

jQueryUI does keep an internal "state" of "snapped" elements, but you have to work a little to get at it.

You're going to want to define an event handler for the stop event (which is called when a draggable object is stopped dragging).

An array called snapElements is maintained inside the widget data, and it looks something like this:

[ 
    { 
        height: 102, 
        item: { /* DOM element */ }, 
        left: 10, 
        snapping: false, 
        top: 10, 
        width: 102 
    }, ...
]

What we really care about here is the item and snapping properties. snapping will tell us if the item is currently "snapping" to a draggable object.

With this array in mind, we can write code like this to determine the snappable targets that are currently "snapping":

$(".draggable").draggable({
    snap: ".snap",
    stop: function(event, ui) {
        /* Get the possible snap targets: */
        var snapped = $(this).data('draggable').snapElements;

        /* Pull out only the snap targets that are "snapping": */
        var snappedTo = $.map(snapped, function(element) {
            return element.snapping ? element.item : null;
        });

        /* Process the results in the snappedTo array! */
    }
});

The reason that your end result is an array and not a single DOM element is that jQueryUI is actually smart enough to realize when you've snapped a draggable to two "snappable" elements.

Here's a working example that shows all of this in action: http://jsfiddle.net/andrewwhitaker/uYpnW/5/

Hope that helps.

like image 109
Andrew Whitaker Avatar answered Dec 01 '22 18:12

Andrew Whitaker