I'm looking for a javascript function that calculates a snap to grid value using a uniformly spaced grid.
Now I have the following code, which works fine as a basic solution, but now I need it to snap only when within say 2px of the snap position e.g. using a 30px spaced grid and a 2px limit, it would snap between 0px and 2px, 28px and 32px, 58px and 62px, etc.
snapToGrip = function(val,gridSize){
return gridSize * Math.round(val/gridSize);
};
Many thanks
Have you consider using jquery UI? The draggable utility allows snapping.
If you really need to implement it, this returns null when you shouldn't snap.
To snap on both side :