Preserving Existing Events in JavaScript

July 08, 2009

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:

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

#1. João Pedro on July 08, 2009

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!

#2. Staicu Ionut on July 09, 2009

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

#3. Alex on July 11, 2009

I use a oo-version of these functions in my projects:
http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html

#4. JohnGalt on July 19, 2009

Great javascript tutorial. Added this to http://tutlist.com

#5. Aotearoan Blue on July 20, 2009

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.

Leave a comment

Comment in textile images by gravatar