Jquery Ui Draggable, Snapping To A Grid
Solution 1:
Check the snapping example on the Jquery UI Site:
http://jqueryui.com/demos/draggable/#snap-to
You can take their same example and specify both a grid and a snap parameter.
Then the snap will be based off of the top left corner of the snap selector.
$( "#draggable5" ).draggable({ snap: ".ui-widget-header", grid: [ 80, 80 ] });
The example on the Jquery site will now let the "80x80" box snap based on the big container.
In your situation it might be easiest to create a div with 100% width and height, then set the snap: selector (using css selectors) to that div, then specifying a grid to snap to...
Good Luck
Solution 2:
Maybe you could try to round the starting position to the nearest 20 pixels by using the start event on the draggable.
Something like (untested...):
$('#draggable').draggable(
{snap : grid: [20,20]},
{start : function(event, ui) {
var startPosition = $(ui.draggable).position();
$(ui.draggable).css({
'left' : (Math.round(startPosition.left/20)*20)+'px',
'top' : (Math.round(startPosition.top/20)*20)+'px'});
}
}
);
I'm trying myself to achieve that but I'm cloning the dragged element to another container so that's even more tricky ;-) I still have to figure out how to set the position of the helper in the start event...
Of course it will only work if the starting position is already absolute (like when dragged).
As a matter of fact, I've nearly achieved it by applying this method to the stop event and removing the grid property.
You don't get any visual feedback when moving the object around because there's no grid per se anymore, but when dropping it, it goes to your own grid:
stop: function(event, ui) {
var stopPosition = $(ui.draggable).position();
$(ui.draggable).css({'left' : (Math.round(stopPosition.left/20)*20)+'px', 'top' : (Math.round(stopPosition.top/20)*20)+'px'});
}
Here's a working example: http://jsfiddle.net/qNaHE/3/
Post a Comment for "Jquery Ui Draggable, Snapping To A Grid"