I'm removing an html element with .remove() method and at the same time for this element I have an event handler but it is not triggered. Why can that be? Here is the jsFiddle and code: HTML
<span id='del_span'>Delete</span><br>
<span id='to_del'>I'm going to be deleted</span>
JS
$('#del_span').click(function() {
$('#to_del').remove();
});
$('#to_del').on('remove', function() {
alert("I'm being deleted"); //is never triggered
});
The remove()
method doesn't automatically trigger a remove
event (because no such event exists), you can do it manually though, with a custom event:
$('#del_span').click(function() {
$('#to_del').trigger('remove').remove();
});
$('#to_del').on('remove', function() {
alert("I'm being deleted"); //is never triggered
});
JS Fiddle demo.
Incidentally, in those browsers that support mutation events you could use:
$('#del_span').click(function() {
$('#to_del').remove();
});
$('body').on('DOMNodeRemoved', '#to_del', function() {
alert("I, " + this.id + " am being deleted");
});
JS Fiddle demo.
References:
trigger()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With