I'm trying to add elements to the page as the user scrolls down. When the last element comes into view fully I want the observer callback to be called, a new element created, the observer set up to observe the new element and to no longer observe the current target.
function observerCallback(entries, observer) {
entries.forEach((entry) => {
const newDiv = document.createElement('div')
observer.observe(newDiv)
document.body.appendChild(newDiv)
observer.unobserve(entry.target);
});
}
However this doesn't work as I expect it to and the callback just keeps getting called and new elements are spawned. I've set up a codepen to demonstrate the issue.
Why does this happen?