2

I have following type of code

<div id="parent-div">
  <div id="child-div">
    <!--content goes here -->
  </div>
</div>

The child div comes from third party service it will get attached or removed dynamically. How to fire a javascript event during attaching the are removing the div

Praveenkumar
  • 921
  • 1
  • 9
  • 28
  • 2
    [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver): _provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification._ – Andreas Dec 03 '15 at 11:21

2 Answers2

0

You have 2 options:

  1. Have a loop - Every x milliseconds, check to see if child-div exists / does not exists
  2. Use the DOM4 MutationObserver - More info on this here. Note: This is only currently supported in Google Chrome browser support

Related question with answer about the DOM4 MutationObserver:

https://stackoverflow.com/a/11141879/5620297

Community
  • 1
  • 1
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
0

if you are using jquery use .trigger(),

in the function or code you attach the child div, after attaching the child div put

$("div#parent-div").trigger("child_div_attached");

in the function or code you remove the child div, after removing the child div put

$("div#parent-div").trigger("child_div_removed");

then you can add event listener to parent div like,

$("div#parent-div").on("child_div_attached", function() {
  //what to do after child div attached
});

$("div#parent-div").on("child_div_removed", function() {
  //what to do after child div removed
});
snvrthn
  • 385
  • 1
  • 10