I have markup something like this.
<div id="sequenced" class="pane overflow-auto">
<table id="sequenced-railcars" class="table table">
<tbody>
<tr>
<td class="railcar-sequence">1</td>
<td class="railcar-number">ABCD123456</td>
<td class="remove-sequence">
<img src="~/images/delete.png" title="Unsequence" role="button" />
</td>
</tr>
</tbody>
</table>
</div>
And I have the following handlers.
// Handle table row clicks
$('#sequenced-railcars').on('click', 'tr', function () {
var $rows = $('#sequenced-railcars tr');
$rows.removeClass('target-row');
$(this).addClass('target-row');
});
// Handle image clicks
$('#sequenced').on('click', '.remove-sequence img', function () {
var $row = $(this).closest('tr');
var railcar = { id: $row.data('id'), number: $row.find('.railcar-number').text() };
if (railcar.id != undefined) {
unsequenceRailcar(railcar);
$row.remove();
resetTarget();
}
});
This works okay. However, in the case where the image click handler is called, the row click handler is called first.
Is there any way to say that when my image is clicked, that the handler for the row click is not triggered? In the case where the image is clicked, the logic for handling row clicks does not apply.
3
Answers
How would the user click #sequenced without clicking #sequenced-railcars?
The latter gets the event and it bubbles up, which is why you see it called first.
Take a look at the concept of "Event Bubbling" – What is event bubbling and capturing?
Here is a handy method that should help you stop the bubbling – https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
You can simply skip calling the row click event on last
td
usingtd:not(:last-child)
Related: How to select not first tr and not last td