Make a draggable element snap to the vertices around it with a high snapTolerance

Make a draggable element 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 but having a high snapTolerance to avoid too much movement of the dragged element. 

Let's say we got a 20x20 physical DOM grid.

Then we got a 50x50 image (or any other not divisible by 20)

Let's call the image vertices x1, x2, y1 and y2.

Here's a detailed image:



Where you can see the black and green lines representing the physical DOM grid... 

Now, taking into consideration that the image can have a dynamic size... for example 130x50, 160x30, etc...

Let's set a snapTolerance of 10px. Meaning that, if the distance between x2 & y2 is less than the assigned snapTolerance which is 10, make the x2 & y2 side snap to the next snappable object (green line), otherwise, it makes a jump of 20px and the x1 & y1 snaps it over the green line.

That is how jQuery UI Draggable currently works but...

Is there any way to avoid making it behave like that? make the x2 & y2 snap to the next vertex around without caring about the snapTolerance logic and having in mind that the image size can be any size, that's the hard part.

Here's a JSFiddle i made so you can see what i'm saying.

In this example i made a 40x40 grid and set a default of 15 snapTolerance, for that case it works good, that's how i would like to make it behave but for all the different image sizes...


I tried changing the snapTolerance during start/drag events depending on the dragged element... but it works bad.

Does any of you guys know how can I solve this? I'm so stucked.

Thanks in advance.