Please recommend a JQuery plugin that handles collision detection for draggable elements

Jim picture Jim · Apr 21, 2009 · Viewed 14.4k times · Source

We're using the Draggable JQuery UI plugin and need to disallow overlapping among our elements. We could write some collision detection ourselves but would prefer to use a tested package. Any suggestions?

Answer

eruciform picture eruciform · May 19, 2011

You can try jquery-collision plus jquery-ui-draggable-collision. Full disclosure: I just wrote and released these on sourceforge.

The first allows this:

var hit_list = $("#collider").collision(".obstacle");

which is the list of all ".obstacle" that overlap "#collider".

The second allows:

$("#collider").draggable( { obstacle: ".obstacle" } );

Which gives you (among other things), a "collision" event to bind to:

$("#collider").bind( "collision", function(event,ui){...} );

And you can even set:

$("#collider").draggable( { obstacle: ".obstacle", preventCollision: true } );

to prevent "#collider" from ever overlapping any ".obstacle" while dragging.