Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Draggable: Is it possible to snap to grid after mouse release?

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)

like image 381
ErnieStings Avatar asked Mar 01 '23 11:03

ErnieStings


2 Answers

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);
},
like image 67
Ruttyj Avatar answered Apr 09 '23 17:04

Ruttyj


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);
  }
  ...
});
like image 40
Zed Avatar answered Apr 09 '23 18:04

Zed