Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Draggable animation whilst snapping to a grid

jQuery UI Draggable offers a grid option which, when set, will snap your draggable element to a grid. The only problem I'm having with this is I still want it to animate before snapping.

If my grid is [500,500] then there will be no user feedback until the mouse covers a distance of 500px.

Is it possible to do a similar "snap to grid" thing but also animate at the same time?

like image 513
Sam Avatar asked Apr 09 '11 14:04

Sam


1 Answers

I presume you mean you want to snap to a grid after the user has finished dragging. In this case, you can make use of the draggable's stop event and calculate the element's offset.

Assume you have a draggable contained within a parent element, starting at offset (0, 0), which is the top-left hand corner. You then apply a regular draggable effect to the element, and on stop you calculate its position and snap it to the nearest "cell".

The code for this would look something like:

$(el).draggable({
  stop: function(e, ui) {
    var elem = ui.helper,
        left = elem.position().left,
        top  = elem.position().top;

    elem.css({
      left: left - (left%10),
      top: top - (top%10)
    });
  }
});

This code will always snap based on the element's top-left pixel co-ordinate, and relies on the element being absolutely positioned and the parent being non-statically positioned (relative, absolute, etc.)

** Edit **

I have created a quick demo - http://jsfiddle.net/LQwMe/1/

like image 94
Gary Chambers Avatar answered Sep 22 '22 01:09

Gary Chambers