script.aculo.us Confine Draggable

2nd January 2008

Creating a new Draggable object with the script.aculo.us framework is easy. You just create a new instance of the Draggable object with the element id to be made draggable as the first parameter and a set of options as the second.

  1. <div id="dragMe"></div>
  2. <script type="text/javascript">
  3. new Draggable('dragMe',{revert:true});
  4. </script>

The revert option will make the draggable element move back to the position it started from. More options can be added by separating them by commas, so to enable ghosting on the element as well as revert use the following.

new Draggable('dragMe',{revert:true,ghosting:true});

Ghosting means that when the element is dragged a ghost copy of the element moves with the mouse, where the original stays where it is until the mouse is released.

The snap parameter can be used to confine the element to a parent node. Snap is used to make the element move in blocks of a certain number rather than smoothly, this is a special parameter as it can take a number of different formats. These are as follows:

To turn snapping off set the value to false.

new Draggable('dragMe',{revert:true,ghosting:true,snap:false});

To set the same value for x and y use a single parameter.

new Draggable('dragMe',{revert:true,ghosting:true,snap:25});

To set different values for x and y use an array notation.

new Draggable('dragMe',{revert:true,ghosting:true,snap:[25,50]});

A call back function can also be used to set up your own snapping behaviour. This is where you can do set up a constraint so that the draggable element doesn't leave the area of it's parent element.

  1. new Draggable('dragMe',{revert:true,ghosting:true,snap: function(x,y,draggable) {
  2. function constrain(n, lower, upper) {
  3. if (n > upper) return upper;
  4. else if (n < lower) return lower;
  5. else return n-(n%10);
  6. }
  7. element_dimensions = Element.getDimensions(draggable.element);
  8. parent_dimensions = Element.getDimensions(draggable.element.parentNode);
  9. return[
  10. constrain(x, 0, parent_dimensions.width - element_dimensions.width),
  11. constrain(y, 0, parent_dimensions.height - element_dimensions.height)];
  12. }
  13. });

When the draggable element moves over the edge of the parent element the snap value is set to the upper or lower limit of the parent element (depending on where the element is being dragged). Otherwise the current position is used, which means that it snaps to where the mouse is.

This function is called every time a mouse move event is detected whilst the specified element is being dragged so be careful when adding any alert statements if you are trying to debug the code.

Add new comment

The content of this field is kept private and will not be shown publicly.