jQuery UI Draggable Grid & Snap Callback
I had the unfortunate privilege of discovering a minor bug logic flaw in the jQuery UI $.draggable() function. But first, a bit of background: I’m working on a worklfow creation tool in which states are created and assigned actions. States can be linked via a four point anchor system, which is where things get a bit messy. Our draggable state DIVs are set up to use a 6x6 grid, meaning they physically snap while being dragged around the canvas area.

![]()
The problem: the drag callback function is fired before snapping and gridding is applied.
In the case of the workflow tool, raphaelJS arrows linking the states are rendered to the anchor points to demonstrate a relationship. If this redrawCanvas() function of mine is fired on the drag event, the snapped value has not yet been applied to the object. As a result, the arrows can be off by as much as 50% of a grid while dragging.

Above: An example of a grid-snapped state not aligning to its arrow.
Comments in the source code indicate this was intended for plugins and callbacks to alter the position value before it is applied:
Call plugins and callbacks and use the resulting position if something is returned
![]()
The hack: there’s no quick and easy future-proof way of fixing this for everyone, so I slipped in my own little callback into the source. It’s not ideal, but it works perfectly for our needs. In line 178 of jquery.ui.draggable.js I entered the following:
if(this.options.snapCallback) {
this.options.snapCallback();
}
And then it’s just a matter of changing your:
drag: function() { }
To a snapCallback, ensuring it will run once the position has been applied to the objects:
snapCallback: function() { }
Alternatively, your code can remain in the ondrag event - but moving it to the snapCallback ensures the styles have been applied and the DOM is updated. If anyone has a better idea (moving the drag trigger would break plugins) then please do let me know!
4 Notes/ Hide
-
psdtohtmlshop reblogged this from taitems
-
rankandfile likes this
-
jotarun likes this
-
taitems posted this