0

My goal is to perform a certain operation each time an element with a certain id or class is deleted from DOM. Prior to this, I've been successfully using a standard syntax for binding click events on dynamically created elements like this:

$(document).on('click', '.someClass', function(e) {
    alert("Div was clicked");
  });

Inspired by this post, I tried to do the same thing for REMOVE event listener, and failed. Here is my jsFiddle.

Any hints on how to make this work? And maybe what I am trying to do is fundamentally wrong, and I should come up with some entirely different logic ?

http://jsfiddle.net/wphtjw1o/

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121
  • Note, in the linked post it says you need to load _jQuery UI_ as well – Asons May 13 '18 at 10:00
  • 1
    Check this post too: https://stackoverflow.com/questions/18410050/jquery-remove-method-doesnt-trigger-onremove-event – Asons May 13 '18 at 10:09

2 Answers2

0

This is the functionality of Jquery UI script, so you have to include two scripts Jquery and Jquery UI to make it work.

$(function() {
  $('<div id="DivToBeRemoved">DIV TO BE REMOVED</div>').prependTo('body');
  $("#DivToBeRemoved").on("remove", function () {
        alert("Element was removed");
    });

  $(document).on('click', '#DivToBeRemoved', function(e) {
    alert("Div was clicked");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>

   
<button onclick="RemoveDiv();">Click here to remove div above</button>
<script type="text/javascript">
  function RemoveDiv() {
    var d = $("#DivToBeRemoved");
    d.remove();
  }

</script>
Ihor Lavs
  • 2,315
  • 2
  • 15
  • 26
0

If I got you correctly, you trying to write custom event (remove event in your case).

For calling custom event you don't need any library, you need to trigger that event, like so:

function RemoveDiv() {
    var d = $("#DivToBeRemoved");

    // d.remove();
    d.trigger('remove'); // <--
}

Read more about trigger: .trigger()

Also check this question here on SO: Custom events in jQuery?

jsfiddle

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64