Attaching functions to events in JavaScript: The unobstrusive way!

Posted by Enrique Delgado Thu, 03 May 2007 15:33:00 GMT

I needed to set a simple focus when a page loads in a legacy site I was working on so I decided to exercise a “better way” to attach functions to events in JavaScript.

In the past, I used to attach onLoad events through an anonymous function like so:
window.onload = function() {
  init();
}

function init() {
  //do something interesting
}
This method has its drawbacks tho; it assumes that this script is the only script that may act upon a document. We “assume instead that it is part of a whole group of scripts all of which fulfilling different tasks.” As described in this awesome webzine by Chris Heilmann . Instead, Chris points out a better solution; something unobstrusive (because you don’t have to mix JavaScript with HTML) and that plays well with others (because more than one script can act upon a document):
  // Attach the function init() to the window.onload event:
  addEvent(window,'load',init,false);

  // Initialization; I'm setting the focus on the first field:
  function init() {
    //do something interesting
  }

  // Function to attach events to objects.
  // (http://icant.co.uk/articles/from-dhtml-to-dom/from-dhtml-to-dom-scripting.html#domasset3)
  function addEvent(elm, evType, fn, useCapture){
    if (elm.addEventListener)
    {
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent) {
      var r = elm.attachEvent('on' + evType, fn);
      return r;
    } else {
      elm['on' + evType] = fn;
    }
  }

The key here is the way addEvent adds event listeners to the document.

Posted in  | Tags ,  | 2 comments

Comments

  1. 1.
    Avatar Aidan Fraser said 3 months later:
    Nice.

  2. 22.
    Avatar Allie said about 1 year later:
    My bf is such a nerd... but i LOOOOOOVE him :)

(leave url/email »)

   Preview comment