Preserving Existing Events in JavaScript
If you are creating a JavaScript library for people to use, you want to make sure that you aren’t overriding existing JavaScript events that your users may have already attached.
Existing Event
window.onclick = function(e) {
alert(‘existing event’);
}
Creating a New Event
If we want to preserve that existing event, we need to follow these steps:
- Wrap the new event definition in a closure to capture the existing event.
- Fire the existing event if it is defined, making sure it has not returned false.
- Continue with new event.
window.onclick = (function(e){
var windowClick = window.onclick;
return function(e){
if (windowClick != null && windowClick() === false) {
return false;
}
alert(‘new event’);
return true;
}
})();
This will alert, “new event” so long as the existing event does not return false. If we want to prevent the new event, we can simply return false on our original event like so..
window.onclick = function(e) {
alert(‘existing event’);
return false;
}
5 comments
Hello Marc,
Very nice article, congratulations!
I am sharing this on my blog in portuguese:
http://www.joaopedrobarros.com.br/2009/07/08/presenvando-eventos-existentes-em-javascript/
There are a link to the original article.
Thank you, bye bye!
Nice article!
However, one of the problem i encountered is somehow related to this: how do i clone events? Let’s say i have a container with many elements inside of a TD, and each element have at least one event on it. And i want to move that container in another TD (or even on another table) (somehow like sortable works). How should i do it? What is the trick?
Thanks :D
I use a oo-version of these functions in my projects:
http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
Great javascript tutorial. Added this to http://tutlist.com
Nice piece; but why not use event listener (/attachment/bind) to add events to DOM elements rather than using .onclick? That way, we won’t have to worry about pre-existing event handlers.