Add an event handler

I keep using this snippet of code:

if( window.addEventListener ) {
window.addEventListener("load", fn, false );
} else if( window.attachEvent ) {
window.attachEvent("onload", fn );
}

It’s just a tidier way of attaching a function ‘fn’ to an event. It also allows multiple handlers per event. There could be another ‘else’ where we just assign the function to an event (e.g. window.onload = fn ) but that would only support one handler per event.

Advertisements
Add an event handler

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s