agis agis - 6 months ago 31
Ajax Question

continuously check if something exists and do something

The content on my page is loaded via AJAX (it's a step by step process) and I need to check if a specific div exists.

That specific div appears after few clicks. I have to mention that I don't know the number of clicks.

How can I continuously check if the div exists till it finds it and after it finds it do to something?

Later edit:
How can I continuously check till a specific div doesn't exist and do something after that. More exactly the div is there, but after a few ajax calls it gets removed.

Answer

If you can't control the AJAX load, this might be a solution for you.

Use DOMSubtreeModified event, which will allow any method, click or what ever, to add (or remove) content and it will be detected.

(function(doc,found) {
  window.addEventListener('DOMSubtreeModified', function() {

    var yourdiv = doc.querySelector("#yourdiv");

    if(found && !yourdiv){
      // Was there but is gone, do something
      found = false;

    }

    if(yourdiv){
      // Found it, do something
      found = true;

    }

  }, false);
})(document,false);

It work like this, when content is inserted (or removed) the event fires and check for your specific div.

It also has benefits of not being called every nn second, like a timer, nor being processed on every click, only when DOM changed.


As commented by @metarmask, DOMSubtreeModified is deprecated but has still a better cross browser coverage than the newer MutationObserver.

An equivalent sample using the newer method would be

(function(doc,found) {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {

          var yourdiv = doc.querySelector("#yourdiv");

          if(found && !yourdiv){
            // Was there but is gone, do something
            found = false;

          }

          if(yourdiv){
            // Found it, do something
            found = true;

          }

        });
    });
    observer.observe(doc, { childList: true, subtree: true });
})(document,false);
Comments