Basically, i want to use the grid option to snap a draggable div toa 30 x 30 grid but i want to keep the dragging smooth. So is there a way i can snap to the grid on mouse release (or something similar)
correction to @Zed this will use the center for deciding which grid to place it in. which ever most of the draggable is in is the one it goes.
stop: function(e, ui) {
var grid_x = 30;
var grid_y = 30;
var elem = $( this );
var left = parseInt(elem.css('left'));
var top = parseInt(elem.css('top'));
var cx = (left % grid_x);
var cy = (top % grid_y);
var new_left = (Math.abs(cx)+0.5*grid_x >= grid_x) ? (left - cx + (left/Math.abs(left))*grid_x) : (left - cx);
var new_top = (Math.abs(cy)+0.5*grid_y >= grid_y) ? (top - cy + (top/Math.abs(top))*grid_y) : (top - cy);
ui.helper.stop(true).animate({
left: new_left,
top: new_top,
opacity: 1,
}, 200);
},
If that is all you want to do with the grid, you could emulate it:
$("#myobj").draggable({
...
stop: function(event, ui) {
t = parseInt($(this).css(top);
l = parseInt($(this).css(left);
$(this).css(top , t - t % 30);
$(this).css(left, l - l % 30);
}
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With