Make your life easier with event delegation

Event delegation is a simple javascript idom that spares you from a lot of hard work. In case you have a list of items (like <table> or <li>) there is no need to start to add an event handler like onclick to every single row/list item. Instead it is enough to just add a single handler on the table/list itself.

If you ever used javascript (especially if you are using a library like JQuery) maybe you already added elements to your page retrieved by an ajax call and notice that nothing happens then you click them since you need to manually add an event handler to them. In this respect Javascript is very different to CSS. In CSS all styles get applied automatically even if an element gets added to the page later (more on the great tutorial on learning jquery). However “behaviour stylesheets” would be a really nice feature to write unobstrusive javascript.

Things get easier then using event delegation. Every time you click on a row of your table your event handling function will be invoked. The event information will be passed as an argument to it. The nice thing is that the event handling will work automatically even on newly added rows. For cross browser event handling, you might take a look at quirksmode or simply use one of the major javascript libraries. The following examples uses JQuery.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>js test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"> </script>
<script type="text/javascript">

$(function(){
  $('#tlist').bind("click", function(event) {
    rowClicked(event.target.parentNode);
  });
});

function rowClicked(r) {
  alert(r.innerHTML);
}

</script>
</head>

<body>
<table id='tlist' border="0">
  <tr>
    <th>id</th><th>value</th>
  </tr>
  <tr>
    <td>1</td><td>One</td>
  </tr>
  <tr>
    <td>2</td><td>Two</td>
  </tr>
  <tr>
    <td>3</td><td>Three</td>
  </tr>
</table>
</body>
</html>

One of the libraries leveraging event delegation is reglib. Another option might be the JQuery plugin LiveQuery and others. Starting from version 1.3 JQuery offers the methods “live” and “die” that provide some simple event delegation features.

These libraries attach event handlers to the document itself (since every element bubbles up there eventually) that choose the function to call based on the selector the event.target fits too. Even if this is not the optimal solution for every application, I hope you consider the use of event delegation on <tables> and <li> instead of attaching an eventhandler to every single row.

Advertisements