Attaching functions to events in JavaScript: The unobstrusive way! - Part 2

Posted by Enrique Delgado Fri, 24 Oct 2008 13:00:00 GMT

Previously, I talked about a good way to attach event listeners to DOM elements. I like the approach described in that post because is pure JavaScript and not dependent on a framework, but if you happen to be using a framework already, or are thinking on using some, here are two methods of achieving this task:

It is important to remember that, your code should wait for the DOM tree to completely load before attempting to attach events to elements. The typical scenario is that some JavaScript code is attempting to attach an event to an element that does not exist yet, because the document is still loading.

Each framework has ways of wrapping your code, so that it runs only when the DOM is ready:

  • Prototype
    document.observe("dom:loaded", function() {
      // Your code here
    });
    
  • jQuery
    $(document).ready(function(){
       // Your code here
     });
    
    

Using Prototype

Prototype offers several event handling methods, but the most common is observe and stopObserving.

Example:

$('foo').observe('click', respondToClick);

function respondToClick(event) {
  // This is how you access the element that triggered the event:
  var element = event.element();
  // Your code here, e.g.:
  alert('Hello');
}

Notice the name of the event, in this case is click. The complete list of events are defined in the W3C recommendations, but here is a summary of the most common event names organized by type:

  • Mouse Events
    • click – Occurs when the pointing device button is clicked over an element.
    • mousedown – Occurs when the pointing device button is pressed over an element.
    • mouseup – Occurs when the pointing device button is released over an element.
    • mouseover – Occurs when the pointing device is moved onto an element.
    • mousemove – Occurs when the pointing device is moved while it is over an element.
    • mouseout – Occurs when the pointing device is moved away from an element.
  • Key Events
    • W3C does not have them, but the following are supplied by Prototype:
      KEY_BACKSPACE, KEY_TAB, KEY_RETURN, KEY_ESC, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_DELETE, KEY_HOME, KEY_END, KEY_PAGEUP, KEY_PAGEDOWN
  • HTML Events
    • load – Occurs when the DOM implementation finishes loading.
    • unload – Occurs when the DOM implementation removes a document from a window or frame.
    • select – Occurs when a user selects some text in a text field.
    • change – Occurs when a control loses the input focus and its value has been modified since gaining focus.
    • submit – Occurs when a form is submitted.
    • focus – Occurs when an element receives focus either via a pointing device or by tabbing navigation.
    • blur – Occurs when an element loses focus either via the pointing device or by tabbing navigation.

Using jQuery

jQuery mostly has “helper methods” to set event listeners that are named after the event name, but the two most basic methods are bind and unbind.

Example:

$("#foo").bind("click", function(e){
  // This is how you access the element that triggered the event:
  var element = event.target;
  // Your code here, e.g.:
  alert('Hello');
});
Again, notice the name of the event, in this case is click. According to the jQuery documentation, these are the allowed event names:
  • blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error.

Most helper elements are named after the event names above, so you have things like click(), focus(), submit(), etc.

Example using an anonymous function as the functioned to be executed when the event is triggered:

$("#foo").click(function () { 
  // The element is access by using "$(this)" 
  // Your code here, e.g.:
  alert('Hello');
});

Event Delegation

One often source of confusion is how to attach event listeners to dynamically-generated DOM elements (for example, adding <li> elements to a list via AJAX).

When an element is crated, it is not already bound to an event listener, so you will have to perform a two-step process: create the element in the DOM, and then attach the event listener. This can get tedious easily, so instead of attaching the event listener to the DOM element desired, you attach an event listener to a parent element in the DOM tree.

In turn, this parent element acts as a “catch all” event listener. It will figure out which element triggered the event in the first place and act accordingly. This technique is referred to as event delegation.

Event delegation works because some events “bubble up” from child nodes to parent nodes in the DOM tree; see event bubbling.

Hope thins helps someone out there getting started. Post your questions if you run into trouble. :)

Posted in  | Tags , , , ,  | no comments

Enhance your JavaScript-fu with LowPro

Posted by Enrique Delgado Thu, 31 May 2007 14:34:00 GMT

During RailsConf 2007 I had the pleasure to have a beer with Dan Webb at the Rails Machine hangout. It was cool to talk all about JavaScript (one of my interests) as it relates to Rails.

It was interesting to find out that Rails is not quite adopting the “unobtrusive way” completely. Just look at how the link_to_remote JavaScript code is generated; it mixes content with JS code.

I’m hoping that as Rails gets betetr and better, it will also support better graceful degradation for JavaScript. For now, Dan’s awesome library a.k.a Low Pro should help us all become true JavaScript-fu disciples.

Talk about navigating through the DOM with ninja-like swiftness! :)

Posted in  | Tags ,  | 1 comment

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