0

When div appears on screen, i need to run a function

but since i am new to javascript i couldn't succeed.

how can i do it using intersection observer

<div id='demo'/>

my function

function myFunc() {
    var headID = document.getElementById("demo");         
    var newScript = document.createElement('script');
    newScript.src = '/myscript.js';
    headID.appendChild(newScript);
}

awakening
  • 184
  • 1
  • 11
  • Why would you need an Intersection Observer when you want to do something on hovering? – Emiel Zuurbier Dec 26 '21 at 16:25
  • like lazy loading images – awakening Dec 26 '21 at 16:53
  • See [this](https://stackoverflow.com/questions/67626399/how-to-use-the-observer-to-check-if-a-div-is-visible-or-not-maybe-azure-server) and [this](https://stackoverflow.com/questions/53684503/intersection-observer-call-a-function-only-once-per-element) – aerial Dec 26 '21 at 16:57

1 Answers1

2

In the observer's callback, check for each observed entry if they are interesecting. If they are, then call myFunc() and unobserve the element to only call myFunc once.

function myFunc() {
  const script = document.createElement('script');
  script.src = '/myscript.js';
  demo.append(script);
  console.log('Script appended');
}

/**
 * This is called whenever an observed element is 
 * in view or went out of view.
 */
const onIntersection = (entries, observer) => {
  for (const { isIntersecting, target } of entries) {
    if (isIntersecting) {
      myFunc();
      observer.unobserve(target);
    }
  }
};

/**
 * The options for the observer.
 * 50px 0px on the rootMargin says that the observer triggers
 * after 50px in the top and bottom.
 */
const options = {
  root: null,
  rootMargin: '50px 0px',
  threshold: [0]
};

/**
 * Select the demo element, create an observer and start observing the demo element.
 */
const demo = document.getElementById('demo');
const observer = new IntersectionObserver(onIntersection, options);

observer.observe(demo);
#demo {
  display: block;
  height: 100px;
  width: 100px;
  background: red;
  margin-top: 1000px;
}
<div id="demo"></div>
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32