Modern Event Handling

<script type="text/javascript">
/**
 * Attach an event handler on a given Node taking care of Browsers Differences
 * @param {Object} node
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 */
function addEventHandler(node,type,fn , capture){
       if(typeof window.event !== "undefined"){
                /* Internet Explorer way */
               node.attachEvent( "on" + type, fn );
       } else {
               /* FF & Other Browsers */
               node.addEventListener( type, fn , capture );
       }
}


/* Example */
addEventHandler(window,"load",function(){
   alert("The page was loaded");
},true)
</script>

This is better than doing the traditional "window.onload" event, as it can attach multiple event handlers to a single event and they all get called.

Comments

  1. User Avatar
    Ryan
    Permalink to comment#

    This has be known to be a flaky way of encasulating event handling into a function. attachEvent & addEventListener do not work the same way and will cause issues, see here for good explanation http://www.quirksmode.org/blog/archives/2005/08/addevent_consid.html

  2. User Avatar
    David Walker
    Permalink to comment#

    Ryan is right, this can be flaky and should only be used when you are not going to hit other event issues such as key presses. Else the if should be reversed so the W3C approach comes first. Else when you hit IE9+ which do event handling correctly you force IE into the legacy approach.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag