JavaScript Page 3 - Mouseover Events and Event Delegation in JavaScript |
Modifying the hands-on example that you learned in the previous section to implement event delegation with “mouseover” events requires changing a single line of JavaScript code, and nothing else. To demonstrate this, below I included the respective signatures of the JavaScript functions tasked with applying this approach in conjunction with the sample HTML table created before. Here they are: // 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'; } } // run functions when web page has been loaded window.onload=function(){ if(document.getElementsByTagName&&document. 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); } } }
As I stated before, the only change introduced to the above JavaScript code was the line that assigns a “mouseover” event to the pertinent HTML table, which originally used a click handler. Now, with this minor modification, the cells of the table will be highlighted every time the mouse is moved over each of them. Simple to code and read, right? At this stage, I’m sure that you now understand how the JavaScript functions shown before do their business. So it’s time to include this behavioral layer, along with the CSS code and markup of the previous HTML table, in the same (X)HTML file. This step will complete this particular example. Thus, to see how this brand new file will be created, please read the last segment of this tutorial. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|