I'm using intersection observer in a marquee, where I am observing for when the first child leaves the viewport, removing that first child, shifting the new (identical) first child by its element's width to the right (with marginLeft), and then appending another identical child element to the end of the parent div's children.
This works once, but intersection observer does not fire a second time, even though the new first child is identical to the deleted one.
I was wondering whether mutation observer would be more useful here, but not sure how to go about it!
let firstChild = document.querySelector('.marquee').firstElementChild;
let target = firstChild;
let options = {
root: null,
threshold: 0,
};
function onChange(changes) {
changes.forEach(change => {
if (change.intersectionRatio === 0) {
firstChild.remove();
console.log('Header is outside viewport');
for ( i = 0; i < 100000; i++ ) {
if ( rectParent.childElementCount < 3 ) {
let child = document.createElement('p');
child.className = "global-chat";
child.innerHTML = "Something written here";
let docFrag2 = document.createDocumentFragment().appendChild(child.cloneNode(true));
rectParent.appendChild(docFrag2);
document.querySelector('.marquee').firstElementChild.style.marginLeft = `${boxWidth}` * `${i+1}` + "px";
}
}
}
});
}
let observer = new IntersectionObserver(onChange, options);
observer.observe(target);```
you define the IntersectionObserver class and instantiate it in the observer. at this moment, the firstChild variable gets the proper element, but in the next change, your firstChild didn't get an update!
You can update your firstChild element in the onChange function to ensure get the proper element before changes.
for example:
function onChange(changes) {
changes.forEach(change => {
if (change.intersectionRatio === 0) {
const firstChild = document.querySelector('.marquee').firstElementChild;
firstChild.remove();
// rest of the codes ...
}
});
}