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.
<div id="dragMe"></div>
<script type="text/javascript">
new Draggable('dragMe',{revert:true});
</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.
new Draggable('dragMe',{revert:true,ghosting:true,snap: function(x,y,draggable) {
function constrain(n, lower, upper) {
if (n > upper) return upper;
else if (n < lower) return lower;
else return n-(n%10);
}
element_dimensions = Element.getDimensions(draggable.element);
parent_dimensions = Element.getDimensions(draggable.element.parentNode);
return[
constrain(x, 0, parent_dimensions.width - element_dimensions.width),
constrain(y, 0, parent_dimensions.height - element_dimensions.height)];
}
});
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