Reputation: 6413
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)
Upvotes: 4
Views: 2906
Reputation: 97
A nice little something I just discovered now is, that if you give the dragged element the css property of transition it will have an effect on the speed it snaps to grid.
$(function() {
$(".draggable").draggable({
containment: 'window',
grid: [30, 30]
});
});
.draggable {
background: #333;
color: whitesmoke;
font-family: 'sans-serif', 'arial';
padding: 5px 12px;
display: inline-block;
transition: top 0.05s ease-in-out, left 0.05s ease-in-out
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="draggable">Drag Me!</div>
Upvotes: 0
Reputation: 933
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);
},
Upvotes: 5
Reputation: 57658
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);
}
...
});
Upvotes: 3