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

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.

Leave a Comment