JavaScript Page 3 - Using HTML Lists with Event Delegation in JavaScript |
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.
|
|
|
|
|
|
|
|