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.

Great Web resources


Author's first example code:
// Classic event handling example
(function(){
  var resources = document.getElementById('resources');
  var links = resources.getElementsByTagName('a');
  var all = links.length;
  for(var i=0;i<all;i++){
    // Attach a listener to each link
    links[i].addEventListener('click',handler,false);
  };
  function handler(e){
    var x = e.target; // Get the link that was clicked
    alert(x);
    e.preventDefault();
  };
})();

Author's second example code:
(function(){
  var resources = document.getElementById('resources');
  resources.addEventListener('click',handler,false);
  function handler(e){
    var x = e.target; // get the link that was clicked
    if(x.nodeName.toLowerCase() === 'a'){
      alert('Event delegation:' + x);
      e.preventDefault();
    }
  };
})();

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

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