Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda