Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Execute a function when a div is visible, using the intersection observer

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);
}

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!