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:
- Prototype.js: observe method.
- jQuery: bind method and friends.
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
- W3C does not have them, but the following are supplied by Prototype:
- 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. :)





