JavaScript Page 3 - Using Event Delegation for Mouseover Events in List Items |
Since my plan here consists of demonstrating how to use event delegation when the mouse is placed over the items of an HTML list, I’m going to use the same list that you saw in the previous section of this tutorial. This way you can understand more easily how this approach can be employed with different mouse events. Here’s a basic (X)HTML file that includes the aforementioned list, along with a few simple CSS styles. Take a look at it, please: <!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> <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 mouseover 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> I’m not going to waste your valuable time explaining how the above (X)HTML file functions, since that would be completely pointless. It’s enough to say that it includes the pertinent HTML list, whose behavior naturally must be extended via some unobtrusive JavaScript. However, as I anticipated in the introduction, this process will be carried out by means of the event delegation approach, which in this case will be used for highlighting the items of the list by using one single “mouseover” handler. To illustrate more clearly how this task will be performed with JavaScript, in the following segment I’m going to build a brand new (X)HTML file, which will contain not only the HTML list created before, but the portion of JavaScript that changes the background color of the respective items. Now, jump ahead and read the last section of this tutorial. We’re almost done.
|
|
|
|
|
|
|
|