Search code examples
jqueryevent-bubbling

Handle event bubbling in jquery


I have a simple HTML table looking something like this

 <table id='resultGrid'>
   <tr>
      <td>
        <a href='javascript:callAction(xxx)'>Johnny</a>
      </td>
      <td>
         Active
      </td>
   </tr>
   <tr>
      <td>
        <a href='javascript:callAction(yyy)'>Nitro</a>
      </td>
      <td>
         In Active
      </td>
   </tr>
 </table>

and i wanted to handle both row clik and hypherlink click. Since the hepher link is already attached to callAction() function, i used jquery to add click event to the row

$("#resultGrid tr").each(function(){
        $(this).css('cursor','hand');
        $(this).click(function() {
             //My logic
        });
});

Now problem is everytime i click the hyperlink, the row click event also fires. How can i prevent this.


Solution

  • you could use e.target.nodeName

    $("#resultGrid tr").each(function() {
        $(this).css('cursor', 'hand');
        $(this).click(function(e) {
            alert(e.target.nodeName.toLowerCase() != 'a');
        });
    });
    

    demo