Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind dynamically generated element to Intersection Observer?

This is the code that I'm using:

var ob = new IntersectionObserver(entries => {
    for(var entry of entries){
        console.log('works');
    }
});

document.querySelectorAll('dynamicElement').forEach(elem => ob.observe(elem));

This is working for elements that are on the page, but it doesn't work for elements that get dynamically created later. How do I bind an element that's inserted in the page later ?

I know with jquery you can bind it like $(document).on('event', 'element', 'func');, but how do I do it with the observer ?

like image 368
Marcel Avatar asked Apr 09 '26 23:04

Marcel


1 Answers

Old question but basically I had the same problem recently and did not find any answer on the net so after investigating the obvious solution was to use the MutationObserver() API together with IntersectionObserver().

Basically you choose a non-dynamic parent of the dynamically generated children elements and attach a mutationObserver to its childList.

Subsequently on mutation detected (on the mutation observer callback) you select the dynamically generated element and attach the intersection observer to it.

Additionally if you use a querySelectorAll you can also use a forEach to attach an intersection observer to all the dynamic elements you wish as you were suggesting on your question.

Something like:

// Mutation Observer
   
const mSection = chatSection.querySelector(".non-dynamic-parent"),
    mObsOptions = {
      childList: true,
    },
    mObserver = new MutationObserver(mObs_CB);

  function mObs_CB(mutations) {
    for (let mutation of mutations) {
      if (mutation.type === "childList") {
        console.log("Mutation Detected");        

        //Start the Intersection Observer Here
        const intObsAllElem = document.querySelectorAll(".dynamicElement");        
        intObsAllElem.forEach(function (elem) {
          intObserver.observe(elem);
        });
      }
    }
  }

  mObserver.observe(mSection, mObsOptions);

 
//Intersection Observer
  
   const intObsOptions = {
         root: null,
         threshold: 1,
         rootMargin: "0px",
    },
    intObserver = new IntersectionObserver(intObs_CB, intObsOptions);

  function intObs_CB(entries, observer) {
      entries.forEach((entry) => {
         if (entry.isIntersecting) {
            console.log("intersecting");
         } else {
            console.log("not intersecting");
         }

      });

  }
like image 73
electronixG Avatar answered Apr 12 '26 11:04

electronixG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!