1

I want to make items in a table draggable, but they have to also snap to a grid. If the items are different sizes, how can I manage that? It would be best if I can do it with jQuery.

Edit: I have a 3 x 4 table, and each td is a 50 by 50 px square. How can I use JQuery to make divs in the td cells be draggable, but they always snap to a td cell? (kind of like on the windows desktop, you can make apps snap to an invisible grid)

1 Answers1

2

I'm going to go ahead and post an answer here, too, though I came here via a followup question you asked.

You can create your own snap-to-grid functionality very easily inside the drag event on a jQuery UI draggable.

Basically, you want to check how close the current UI position is at any point that the draggable is being dragged to a grid. That proximity can always be represented as the remainder of the position divided by the grid. If that remainder is less than or equal to the snapTolerance, then just set the position to what it would be without that remainder.

That was weird to say in prose. In the code it should be more clear:

Live Demo

// Custom grid
$('#box-3').draggable({
drag: function( event, ui ) {
    var snapTolerance = $(this).draggable('option', 'snapTolerance');
    var topRemainder = ui.position.top % 20;
    var leftRemainder = ui.position.left % 20;

    if (topRemainder <= snapTolerance) {
        ui.position.top = ui.position.top - topRemainder;
    }

    if (leftRemainder <= snapTolerance) {
        ui.position.left = ui.position.left - leftRemainder;
    }
}  
});
Sterling Silver
  • 243
  • 1
  • 13