Tip - Unhooking Events

Say you've hooked an event on a div called "myDiv" like so:

$('myDiv').observe('click', doSomething);

(Perhaps because you used this tip or worked through this "how to".)

You can unhook it via Event.stopObserving.

// Using Event.stopObserving as a static call...
Event.stopObserving('myDiv', 'click', doSomething);
// ...or using the methodized version:
$('myDiv').stopObserving('click', doSomething);

To unhook a specific handler (as above), the call to stopObserving must have exactly the same parameters as the call to observe did originally, including the same function reference.

Alternately, you can remove all 'click' event handlers from the div by leaving the handler parameter off:

// Static call...
Event.stopObserving('myDiv', 'click');
// ...or methodized:
$('myDiv').stopObserving('click');

In the above, all 'click' handlers hooked up via Event.observe will be unhooked.

You can also remove all event handlers for all events from the div (well, those that were hooked via Event.observe) by leaving off the event name:

// Static call...
Event.stopObserving('myDiv');
// ...or methodized:
$('myDiv').stopObserving();

This is handy when you're about to remove the element from the page and don't want to leave handlers lying around.

For more, see our supplemental API page for stopObserving.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License