Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda