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

203
Vistas
Using Intersection Observer and EventListeners || Registering keypresses only while specific element is visible

I'm attempting to add an event listener to the document element, which remains active only while a specific section element is within the visible portion of the viewport.

This listener listens for two keypresses, ArrowLeft and ArrowRight, and calls matching functions moveLeft() and moveRight() for each case. Once the section is no longer visible within the viewport the eventListener is to be removed.

const cObserverHandler = entries => {
    const [entry] = entries;

    const keyListener = e => {
        if (e.key === 'ArrowLeft') moveLeft();
        else if (e.key === 'ArrowRight') moveRight();
    };
    if (entry.isIntersecting) {
        console.log('intersect');
        document.addEventListener('keyup', keyListener);
    } else if (!entry.isIntersecting) {
        console.log('depart');
        document.removeEventListener('keyup', keyListener);
    }
};

For brevity I've excluded the IntesectionObserver setup and larger app functioning.

As well, to those not already familiar, within this context entry.isIntersecting will evaluate to a Boolean value based on whether the aforementioned section is within the visible area of the viewport.

El problema:

Examining the console, the messages 'intersect' and 'depart' fire during my scroll testing at the expected times. However, some further stress-testing has shown that arrow presses are being registered and acted on even after the point at which the listener should be removed. Any thoughts on why this might be?

Thanks for reading.

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