Grow your CSS skills. Land your dream job.

Last updated on:

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. 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. 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.

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".