0

I'm lazyloading an ad into my website, and I can get it to show up only when the user scrolls down far enough, but when the user scrolls back up, the div disappears. I want it so that when the user sees the div for the first time, the ads come and stay there even if he scrolls away. I also don't want the ads refreshing. My code is:

export const handleAds = () => {

  var myAds;

  window.addEventListener("load", function(event){
    myAds = document.querySelector("#theDiv");
    createObserver();
  },false);

  function createObserver(){
    var observer;

    var options = {
      root: null,
      rootMargin: "0px",
      threshold: 0.2
    };

    observer = new IntersectionObserver(handleIntersect, options);
    observer.observe(myAds);

  }


  function handleIntersect(entries,observer){

    for (var i = 0; i < entries.length; i++){
      if(entries[i].isIntersecting){
        //ad script
        }
      }
    }

}
AviG
  • 362
  • 2
  • 14
  • Sounds like you want to float the div to some absolute position on the screen, but ONLY if the user first scrolls to it. Is that correct? – Abel Aug 11 '19 at 20:22
  • well the div is at a certain position on the screen and when it comes into view, that's when I want it shown and the ads in that div @Abel – AviG Aug 12 '19 at 00:08

1 Answers1

2

call unobserve in your callback: https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/unobserve

function handleIntersect(entries,observer){

  for (var i = 0; i < entries.length; i++){
    if(entries[i].isIntersecting){
      //ad script
      observer.unobserve(entries[i]);
    }
  }
}
James South
  • 534
  • 4
  • 15
  • that doesn't work @James-South ; I also get `TypeError: Argument 1 of IntersectionObserver.unobserve does not implement interface Element.` EDIT: your solution did it, tho the argument you fed into unobserve was wrong – AviG Aug 12 '19 at 00:15