msqar
msqar

Reputation: 3020

Draggable element make it snap to the vertices around it with a high snapTolerance

I just wanted to make a grid with a dragged element and make it snap to the vertices around the element I'm dragging. Happens that if the snapTolerance is too high (grid size i.e: 20px) but the asset is not divisible by 20 in size... it won't snap to the next vertex but it will make a 20px jump to the next block. I don't know if I'm being clear but here's a jsfiddle that might help you understand this better.

In this example, I would like the right side to touch the next vertex before the next-block-jump. Is that possible with jQuery UI right now?

I can decrease the snapTolerance but the snappy effect won't be that smooth since the dragged elements may vary in sizes.

I would like to make it stuck on the vertices at all times but have the edges of the dragged element to snap on every vertex around.

$(".draggable-block").draggable({
    snapTolerance: 20,
    snap: '.guide-line'
});

Upvotes: 4

Views: 1564

Answers (2)

Burdock
Burdock

Reputation: 1105

Unfortunatly the JS fiddle either does not illustrate the issue : or the problem is the object cant be divided evenly by the grid (IE: a 60px*60px block does not fit well in a 40*40 grid)

I would suggest you take a look at the Gsap Draggable Library for tackling this issue. It does quite a good job of tackling the issue.

Upvotes: 0

OrangeKing89
OrangeKing89

Reputation: 704

Try using this option instead of snap:

$(".draggable-block").draggable({
    //snapTolerance: 20,
    //snap: '.guide-line',
    //snapMode: "inner",
    grid: [ 5, 5 ] 
});

http://api.jqueryui.com/draggable/#option-grid

It looks like the JQuery UI draggable only snaps with its top left corner and always aligns with the lines at that spot.

You could try to do something on the drag event and see if there is anything helpful on the ui parameter:

http://api.jqueryui.com/draggable/#event-drag

Are you required to use a 20px grid? If not, you could define your grid lines based off the width or height of the draggable.

var grid = $('<div>', {'id': 'grid'});
var gridWidth = $('.draggable-block').width()/5;
var guideLinePos = gridWidth;
var guideLabel = "";
while(guideLinePos <= 1000) {
    if(((guideLinePos - gridWidth) % gridWidth) == 0) {
        guideLabel = "<div class='guide-line vertical-line'></div>";
        $(guideLabel).css( "left", guideLinePos+"px" ).appendTo(grid);
    }
    guideLinePos = (guideLinePos + gridWidth);
}

Upvotes: 2

Related Questions