Using HTML Lists with Event Delegation in JavaScript

Do you enjoy the responsiveness that using event handlers in JavaScript adds to your web site, but feel concerned about the way they can slow down your applications? Fear not; this four-part article series covers event delegation, a technique that can solve this problem in certain situations. This article is the third part of the series.

Event handlers play a fundamental role within any JavaScript application, since they keep track of mouse clicks, keyboard and window events, and so forth. Logically, their existence permits us to develop client-side programs that are much more responsive than an application running in the web server.

However, when overused, event handlers can seriously slow down the performance of a JavaScript program, and in extreme cases can produce complete system hang-ups. Yet, in certain situations (not all) it’s possible to reduce the number of event handlers that will be used within a particular JavaScript application by means of a handy technique known popularly as event delegation.

Essentially, this approach takes advantage of the bubbling phase of a JavaScript event to detect which specific element of a web page triggered that particular event. Obviously, this allows you to decrease dramatically the number of handlers that need to be coded within a particular program, improving its performance and reliability.

Of course, if you’ve already read the preceding installment of this series, you understand the key concepts that surround the implementation of event delegation in JavaScript. In that tutorial I explained how to create a highlighting effect on the cells of an HTML table, by using one single “mouseover” event handler.

Even though this hands-on example was rather simplistic, it illustrated how useful event delegation can be for building compact, efficient JavaScript programs. Nevertheless, the flexibility provided by this approach allows us to implement it with web page elements other than tables.

Therefore, in this third part of the series I’ll be explaining how to implement event delegation with HTML lists. Want to learn more about this topic? Then start reading the next section. 

{mospagebreak title=Implementing event delegation with an HTML table}

Before I proceed to show you how event delegation can be utilized in conjunction with HTML lists, I will list the full source code of the example developed in the previous article. It showed a basic implementation of this approach for creating highlighting effects on all of the cells of an HTML table.

The hands-on example was built as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Example on JavaScript event delegation (with mouseover event)</title>

<script language="javascript">

// get target element (excerpted)

function getEventTarget(e){

 var e=e || window.event;

return e.target || e.srcElement;

}

// check if target is a table cell (excerpted)

function highlightCell(e) {

var target=getEventTarget(e);

if(target.tagName.toLowerCase()===’td’) {

target.className=’highlighted';

}

}

// run functions when web page has been loaded

window.onload=function(){

if(document.getElementsByTagName&&document.getElementById&&document.createElement){

var mytable=document.getElementById(‘mytable’);

if(!mytable){return};

// assign ‘onmouseover’ event handler to table (not cells)

mytable.onmouseover=function(e){

// determine target element and highlight table cell

highlightCell(e);

}

}

}

</script>

<style type="text/css">

table{

width: 500px;

border: 1px solid #000;

}

td{

font: normal 10pt Arial, Helvetica, sans-serif;

color: #000;

background: #9fc;

border: 1px solid #000;

}

.highlighted{

background: #0c9;

}

</style>

</head>

<body>

<h1>Event delegation in JavaScript (with mouseover event)</h1>

<table id="mytable">

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

<tr>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

<td>This is the content of the cell</td>

</tr>

</table>

</body>

</html>

In case the previous code sample doesn’t ring any bells for you, let me quickly explain how it works. In layman’s terms, the event delegation approach is implemented via the “getEventTarget()” and “highlightCell()” functions, which apply the highlighting effect on the table cells by assigning only one “mouseover” handler to the table. Here, it’s clear to see how useful a delegated event can be in  reducing the number of event handlers required by a JavaScript application.

All in all, at this point you should be familiar with the basics for using event delegation with HTML tables. So it’s time to see how this same handy technique can be utilized when working with unordered HTML lists.

This subject will be discussed in depth in the course of the section to come. So, to learn more, click on the link that appears below and keep reading.

{mospagebreak title=Working with unordered HTML lists for event delegation} 

In the segment that you just read, you learned how to implement JavaScript event delegation on a simple HTML table. As I said before, this approach can be used with practically any element of a web document, as long as it supports event assignment.

Naturally, when I talk about any element of a web page, I’m including HTML lists too. Thus, in the next few lines I’m going to define a brand new (X)HTML file, comprised of a basic unordered list. Then, with this file available for testing purposes, I’m going to implement the event delegation approach on the list, so you can see how this technique can be used with other web page elements.

That being explained, here is the file that builds the pertinent HTML list:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Example on JavaScript Event Delegation (with click event)</title>

<style type="text/css">

ul{

list-style: circle;

}

li{

font: normal 10pt Arial, Helvetica, sans-serif;

color: #000;

}

.highlighted{

background: #0c9;

}

</style>

</head>

<body>

<h1>Event delegation in JavaScript (with click event)</h1>

<ul id="mylist">

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

</ul>

</body>

</html>

Since the above (X)HTML file is extremely simple to grasp, I’m not going to bore you explaining how it works. The only detail to note here is that it includes an unordered list, comprised of a few items. That’s all.

However, here’s where things get really interesting, since it’s possible to create a JavaScript program that dynamically changes the background color of each list item in response to mouse clicks. Of course, at first sight it seems that multiple click handlers will need to be assigned to the items to accomplish this task, but that’s not necessary when using event delegation.

By following an approach similar to the one that you learned when working with HTML tables, it’s feasible to assign only one click handler to the whole list, and then via event delegation, determine which item was clicked on.

Therefore, in the last section I’m going to define the JavaScript functions responsible for implementing event delegation on the HTML list you saw above. So go ahead and read the following lines.

{mospagebreak title=Adding a simple behavior to the HTML list}

In the previous segment I coded a basic HTML list, so now it’s time to implement the event delegation approach to create a highlighting effect on each of its items when they are clicked. In this case, instead of assigning an individual click handler per item, only one will be attached to the whole list.

The following segment of code performs the aforementioned task:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Example on JavaScript Event Delegation (with click event)</title>

<script language="javascript">

// get target element (excerpted)

function getEventTarget(e){

var e=e || window.event;

 return e.target || e.srcElement;

}

// check if target is a list item (excerpted)

function highlightListItem(e){

var target=getEventTarget(e);

if(target.tagName.toLowerCase()==’li’){

target.className=’highlighted';

}

}

// run functions when web page has been loaded

window.onload=function(){

if(document.getElementsByTagName&&document.getElementById&&document.createElement){

var mylist=document.getElementById(‘mylist’);

if(!mylist){return};

// assign ‘onclick’ event handler to unordered list (not items)

mylist.onclick=function(e){

// determine target element and highlight list item

highlightListItem(e);

}

}

}

</script>

<style type="text/css">

ul{

list-style: circle;

}

li{

font: normal 10pt Arial, Helvetica, sans-serif;

color: #000;

}

.highlighted{

background: #0c9;

}

</style>

</head>

<body>

<h1>Event delegation in JavaScript (with click event)</h1>

<ul id="mylist">

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

<li>This is a list item</li>

</ul>

</body>

</html>

As illustrated before, only a few short JavaScript functions are required to implement the event delegation approach with the above HTML list. In this example, each time a list item is clicked on, its background color will change. Naturally, the most important detail to note here is that this simple effect is achieved by assigning one click handler to the list. Here’s a screen capture that shows how the items of the previous list are highlighted as they’re clicked on:

This final example concludes this article on using event delegation with JavaScript. As always, feel free to tweak all of the code samples developed in this article to give you more practice in implementing this useful approach within your own JavaScript programs.

Final thoughts

In this third article of the series, I explained how to extend the implementation of JavaScript event delegation to other elements of a web page, such as a simple HTML list. Nonetheless, this educational journey hasn’t fished yet; in the final chapter, I’ll be discussing how to modify the JavaScript application developed previously, so it can respond to “mouseover” events.

Now that you know what the upcoming article will be about, you simply can’t miss it!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan