I have the following HTML-table:
<table>
<tr>
<td>
Row 1
</td>
<td>
<!-- Hidden JSF-button -->
<button class="hide" />
</td>
</tr>
</table>
When I click on a tr
, I trigger a click on the hidden button with JS:
$('table tr').on('click', function(e) {
var $button = $(this).find('button');
console.log('trigger click on', $button);
$button.trigger('click');
});
The click event propagates up, and will cause a never ending loop (can be seen here: http://codepen.io/anon/pen/kDxHy)
After some searching on Stack Overflow, it is clear that the solution is to call event.stopPropagation
,
like this (can be seen here: http://codepen.io/anon/pen/BnlfA):
$('table tr').on('click', function(e) {
var $button = $(this).find('button');
// Prevent the event from bubbling up the DOM tree.
$button
.off('click')
.on('click', function(e) {
console.log('click');
e.stopPropagation();
return true;
});
console.log('trigger click on', $button);
$button.trigger('click');
});
The solution above works. But it feels like a hack, and I don't like it.
Do I have to register a click handler on the on the $button
just to call event.stopPropagation
? Are there any better way(s) of preventing the click event from bubbling?