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

127
Vistas
Make useEffect only run when component is in view (i.e. scrolled down to that component)

i have this code that updates a number from 2019 to 2022 but i want it to only run when the component is in view, meaning if they haven't scrolled to that part of the page the effect shouldn't run


useEffect(() => {
    setTimeout(() => {
        setTitle(2020)
    }, 2000)
    setTimeout(() => {
        setTitle(2021)
    }, 4000)
    setTimeout(() => {
        setTitle(2022)
    }, 6000)
},  []);

at the moment it updates the value even when you haven't scrolled down to that part of the page, is there a way to make useEffect only activate when scrolled to that section of the page or do you need to do it completely differently?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

window.addEventListener('scroll', function() {
    var element = document.querySelector('#main-container');
    var position = element.getBoundingClientRect();

    // checking whether fully visible
    if(position.top >= 0 && position.bottom <= window.innerHeight) {
        console.log('Element is fully visible in screen');
    }

    // checking for partial visibility
    if(position.top < window.innerHeight && position.bottom >= 0) {
        console.log('Element is partially visible in screen');
    }
});

Snippet from https://usefulangle.com/post/113/javascript-detecting-element-visible-during-scroll. Paste your code to the part where an element is fully in view. Remember to query select the element you want to have in view first.

about 4 years ago · Juan Pablo Isaza 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