I’m having an issue with stopping event propagation. Imagine this scenario:
<table id="test">
<tbody>
<tr>
<td class="row"> </td>
<td class="row"> </td>
<td class="row"> </td>
<td class="row"> </td>
<td class="row"> </td>
</tr>
<tr>
<td class="row"> </td>
<td class="row"> </td>
<td class="row"> </td>
<td class="row"> </td>
</tr>
</tbody>
</table>
And then this code:
(function(){
$('td.row').on('click', function(e){
if (! e.isPropagationStopped())
alert('Row clicked!');
});
$('table#test').on('click', 'img.live', function(e){
e.stopPropagation();
alert('Image clicked!');
});
$('td.row').html('<img src="http://fc03.deviantart.net/fs71/f/2011/161/f/c/nyan_cat_avatar_by_oxoxnaminemayxoxo-d3il6gm.gif" class="live">');
})();
Whenever a image is clicked both events are fired. I want that just fires the event on the clicked element. I know that since they are live they are fired once propagation has ended but, is there any workaround?
As far as I’ve investigated, both events are practically the same but srcElement changes from HTMLTableCellElement to HTMLImageElement. Is this cross-browser consistent?
I’ve put a demo in jsFiddle in case you want to watch in action.
Here’s a demo
The problem is the event has to climb to the parent to find a handler for
<img>. So it has to pass through<td>and fires its handler immediately since it’s not a delegated handler.One way to prevent the double event is also add
<td>‘s handler to the table as well. jQuery will then evaluate the two handlers, start with the deepest event and if any of those handlers hase.stopPropagation(), events higher up will not fire.