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");
}
});
}