Search code examples
javascriptmutation-observers

How to use Mutation observer instead of settimeout to append a div


I have js code which appends a div if an element with a particular class is present in the DOM. Here is the code for that. The steps being first creates a div with a partilcular class. Then it checks if the Dom has an element with class id banner , and if it has then it will append the created div using insertBefore. I'am using this because the banner element is dynamically added to the dom and not always present in the Dom. This works fine.

var overlayelem = document.createElement('div');
overlayelem.setAttribute("class", "overlay");

setTimeout(function(){
  var elem = document.getElementById('banner');
  elem.parentNode.insertBefore(overlayelem, elem.nextSibling);
}, 10)

But the problem being I cannot completely rely on setTimeout, I wish to use mutation ovberser to achieve this, So tried using that and code being like this ( Removed the setTimeout )

var overlayelem = document.createElement('div');
overlayelem.setAttribute("class", "overlay");


var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type == "childList")  {
      var elem = document.getElementById('banner');
      if(elem) {
        elem.parentNode.insertBefore(overlayelem, elem.nextSibling);
      }
    }
  })
})

var elemBody = document.getElementById("body")
observer.observe(elemBody, {
  childList: true,
  subtree: true,
})

But this is not working correctly . The site keeps on loading and never stops. Can anybody help in what went wrong in Mutationobersever.


Solution

  • just lost observer.disconnect();?

    observer.observe(elemBody, {
      childList: true,
      subtree: true,
    })
    //like this
    observer.disconnect();