Prevent Javascript onClick Event From Bubbling Up

I recently was working with some code that had an onClick event handler on the <TR> of each row of a table. In one of the columns, a <TD>, there were icons that also had onClick’s on them. Something like:

1
2
3
4
5
6
7
8
9
10
<table>
  <tr onClick='foo()'>
    <td onClick='bar()'>
      <!-- some icons -->
    </td>
    <td></td>
    <td></td>
    ...
  </tr>
</table>

Now if the icons in the first <TD> were clicked, I wanted bar() to fire, but not foo(). Normal behavior is to execute them both.

Turned out there is a simple solution for this with jQuery. Only tested in Firefox, but presumably this works across the board because jQuery is awesome that way.

Add a class to the <TD> called no-event-bubble-up:

1
  <td onClick='bar()' class='no-event-bubble-up'>

And add the following JS to your page:

1
2
3
4
5
6
7
8
9
<script type='text/javascript'>
  $(document).ready(function() {
    $(".no-event-bubble-up").each(function() {
      $(this).click(function(e) {
        e.stopPropagation();
      });
    });
  });
</script>

That’s all that is needed and it worked for me.

Let me know if you find this useful.

Comments