I’ve got a table of message subjects and I’ve made each tr clickable to navigate to the message details page. However there is also a trash icon that the user can click on to mark the message for deletion via $.ajax, this is done by first turning the tr event handler “off”. The problem is that when turning the tr click event handler back on the click is processed and the user is navigated to the details page.
I attempted to add e.stopPropogation(); immediately after the $.ajax call and before the “on” setting of the tr but that prevents the event from being turned on. Adding it after does not prevent the desired behavior.
So my question is, how do I turn the click event back “on” for the tr after having turned it off, but not fire the event off in the process.
Code:
$("#messageTable tbody tr").on("click", function () {
var id = $(this).find('td:first').find('input').val();
window.location.replace('/Messages/Read/'+id);
});
$('.icon-trash').on("click", function (e) {
// turn off tr click to prevent navigation
$("#messageTable tbody tr").off("click");
// grab the message Id from the hidden input
var messageId = $(this).parent().find('input').val();
var tr = $(this).parent().parent();
var request = $.ajax({
url: "MarkMessageForDeletion"
, type: "GET"
, data: { id: messageId }
, dataType: "json"
, async: true
, success: function (data) {
if (data === "1") {
tr.remove();
}
}
});
// turn click back on
$("#messageTable tbody tr").on("click", function () {
var id = $(this).find('td:first').find('input').val();
window.location.replace('/Messages/Read/' + id);
});
});
Since the trash icon is a descendant of the
tr, there’s no need to turn off the event handler on the row. Simply callstopPropagation()(note the spelling, perhaps that’s why it wasn’t working for you?) from your trash icon click handler.Gratuitous live example
For what it’s worth, you can make the code a bit more robust by using
var tr = $(this).closest('tr');rather than.parent().parent().closestfinds the closest matching ancestor.