RameshVel
RameshVel

Reputation: 65887

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.

Upvotes: 0

Views: 483

Answers (2)

Reigel Gallarde
Reigel Gallarde

Reputation: 65284

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

Upvotes: 3

rahul
rahul

Reputation: 187110

You can prevent event bubling by using

e.stopPropagation()

Also you can use CSS to assign styles for your tr elements.

$("#resultGrid a").click(function(e){
    // do your code
    e.stopPropagation(); // prevent event bubbling
});

Upvotes: 1

Related Questions