Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2010/05/05

Addendum To Someone Else's Work

Seven JavaScript Things I Wish I Knew Much Earlier In My Career is the work. I've been poking at it for a little while, reading it while I'm not working hard on another problem.

From this HTML. you want to call functions rather than go to links.
  1. <h2>Great Web resources</h2><ul id="resources">  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>  
  2.   <li><a href="http://sitepoint.com">Sitepoint</a></li>  
  3.   <li><a href="http://alistapart.com">A List Apart</a></li>  
  4.   <li><a href="http://yuiblog.com">YUI Blog</a></li>  
  5.   <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>  
  6.   <li><a href="http://oddlyspecific.com">Oddly specific</a></li>  
  7. </ul>  

Author's first example code:
  1. // Classic event handling example  
  2. (function(){  
  3.   var resources = document.getElementById('resources');  
  4.   var links = resources.getElementsByTagName('a');  
  5.   var all = links.length;  
  6.   for(var i=0;i<all;i++){  
  7.     // Attach a listener to each link  
  8.     links[i].addEventListener('click',handler,false);  
  9.   };  
  10.   function handler(e){  
  11.     var x = e.target; // Get the link that was clicked  
  12.     alert(x);  
  13.     e.preventDefault();  
  14.   };  
  15. })();  

Author's second example code:
  1. (function(){  
  2.   var resources = document.getElementById('resources');  
  3.   resources.addEventListener('click',handler,false);  
  4.   function handler(e){  
  5.     var x = e.target; // get the link that was clicked  
  6.     if(x.nodeName.toLowerCase() === 'a'){  
  7.       alert('Event delegation:' + x);  
  8.       e.preventDefault();  
  9.     }  
  10.   };  
  11. })();  

My take, assuming jQuery:
  1. $( function() {  
  2.     $( '#resources li a' ).click( function() {  
  3.         alert( 'Event delegation: ' + $(this).attr('href') ) ;  
  4.         return false ;  
  5.         } ) ;  
  6.     } ) ;  

Unless I miss a trick, it works the same and uses far fewer lines.

No comments:

Post a Comment