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.

Add an event handler

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.