IntersectionObserver rootMargin don't seem to work correctly

14 Views Asked by At

I am implementing an intersection observer to determine when certain div elements are coming into the viewport and once they are I am triggering a script which loads the google add into the already defined slot. Now the intersection observer currently works when the element comes into 1 pixel of the viewport however I want to extend the viewport by 350px using the 'rootMargin' property defined in the options object. Reading the documentation the target has to be an ancestor of the root element which it currently is, however the root margin is not having any effect what so ever. The current outcome is still the same.

Here is my code.

`let options = {
        root: document,
        rootMargin: '0px 0px 350px 0px',
        threshold: 0,
    };

    const observer = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                console.log(entry);
                if (entry.isIntersecting) {
                    window.dispatchEvent(new CustomEvent("intersecting", {
                        detail: { slotName: entry.target.id }
                    }));
                    observer.unobserve(entry.target);
                }     
            });
        },
        { options }
    );

    const addObservers = () => {
        const middleAds = "inart";
        const readNextAds = 'rect';
        const asideAds = 'rdnxt';
        const mobile = 'minart';
        const observedElement = document.querySelectorAll(`[id^=${middleAds}], [id^=${readNextAds}], [id^=${asideAds}]`);

        for(let i =0; i < observedElement.length; i++) {
            observer.observe(observedElement[i]);
        }
    };`

Can I even use a direct reference to document or do I need to make another div that takes up the current viewport and wraps around the targeted child elements.

0

There are 0 best solutions below