Getting jQuery draggable to snap to specific grid

Viewed 23357

(NOTE: Some have asked similar questions, but were too specific and yielded no usable answers)

jQuery UI's draggable widget has options for snapping to a grid, but no way to set what the grid is relative to.

For example, we've got a clearly defined 20x20 grid in our drop target. A drag item that starts at 0,0 within the drop target will snap in correspondence with the grid. But a drag item that starts at a different location, or outside the drop target, will not line up with that grid.

enter image description here

http://jsfiddle.net/FNhFX/5/

HTML:

<div class="drop-target">
    <div class="drag-item">Drag me</div>
    <div class="drag-item" style="left:87px;top:87px;">Drag me</div>
</div>
<div class="outside-drag-item">Drag me</div>

JS:

$(function() {
    $(".drag-item").draggable({
        grid: [20, 20]
    });
    $(".outside-drag-item").draggable({
        grid: [20, 20],
        helper:"clone"
    });
    $(".drop-target").droppable({
        accept: ".drag-item"
    });
});

Is there any way to snap to a specific grid using jQuery draggable?

2 Answers
Related