JavaScript Page 3 - Event Delegation in JavaScript |
As you hopefully learned at the beginning of this article, event delegation rests its functionality on the “bubbling” phase of a particular JavaScript event. In a case like the example created in the previous section, it’s perfectly possible (and desirable, actually) to utilize it to attach only one click handler to the whole HTML table, and later on, determine what cell triggered that specific event. To accomplish that task in a simple fashion, I’m going to define a couple of JavaScript functions. The first one will be tasked with determining which element of the web page is the source of a specific event, and the second one will be charged with checking to see if this element is a table cell. If it is, then the highlight effect will be applied to it. That’s it. The signature of these JavaScript functions are as following: // get target element function getEventTarget(e){ var e=e || window.event; return e.target || e.srcElement; } // check if target is a table cell function highlightCell(e){ var target=getEventTarget(e); if(target.tagName.toLowerCase()=='td') { target.className='highlighted'; } } As I explained before, all that the first “getEventTarget()” function does is return the source of the web page element that fires a specific event, while the second function, called “highlightCell(),” not surprisingly checks to see if the returned element is a cell table. If this is true, then the “highlighted” CSS class is tied up to it. So what have we achieved in using this approach? Quite a bit, actually. Obviously, the major advantage is that with these handy functions at our disposal, it’s possible to assign one click handler to the HTML table shown in the previous segment, and then implement the highlighting effect only in the cell that was originally clicked. See how useful it is to use event delegation to avoid coding redundant, memory-consuming handlers? I guess you do. However, the best way to grasp the actual functionality of event delegation is by looking over the complete source code that corresponds to the example developed earlier. Thus, in the following section I’m going to list for you all of the parts that comprise the example, so click on the link below and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|