Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .remove() method doesn't trigger .on('remove') event

Tags:

jquery

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
});
like image 455
Max Koretskyi Avatar asked Dec 01 '22 18:12

Max Koretskyi


1 Answers

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().
like image 165
David Thomas Avatar answered Dec 24 '22 09:12

David Thomas