Monday, February 19, 2007

Overriding Scriptaculous Dragging

Scriptaculous is a fantastic javascript library that lets a developer do alot of very cool things very easily. I've been playing with the Scriptaculous drag&drop library for a while now and have come up with a snippet of code that is very usefull if you are dealing with the dragging of complex objects. Sometimes you want the object to drag, but other times the awesome dragging effect might get in the way of another action we want to take place. Let's say I have a dynamic resizing class (which I do), and using this I make this Object resizable by handles, which are children of a wrapper object that I have made Draggable through scriptaculous. While I'm resizing the object, I don't want it to move around the screen with the mouse . . . so i'll need to kill the scriptaculous dragging. The only problem is that I want the object to be draggable again once I'm done with the resize, and I also want the draggable object to be invoked with the same options as it was invoked before. This bit of code is designed to help you do just that:

ExampleClass = Class.create();

ExampleClass.prototype = {

initialize: function(elementId,dragObject) {
this.element = $(elementId);
this.dragObject = dragObject;
this.dragElement =;
this.dragOptions = this.dragObject.options;
this.someEvent = this.eventHandler.bindAsEventListener(this);
Event.observe(this.element, 'mousedown', this.someEvent);

eventHandler: function(event) {
this.someEndEvent = this.endEventHandler.bindAsEventListener(this);

endEventHandler: function(event) {

makeDraggable: function() {
this.dragObject = new Draggable(this.dragElement,this.dragOptions);

killDraggable: function() {

So we pass as an option to the class creation, the drag object . . . for instance if we had the drag object:

testExampleDiv.draggableObject = new Draggable('elementid',{options});

We would pass testExampleDiv.draggableObject to our class. The initialization function then grabs the elementId and the options passed in the initial Draggable object creation from the draggable object and saves it. At the beginning of the event, the script kills the draggable object, and then at the end of the event the script reinvokes the draggable object, passing the elementId of the original object, and the original options object to the Draggables initialization function.

The above example uses prototype, which is a safe assumption if you're using scriptaculous . . .


No comments: