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

92
Visualizações
Attach scroll event handler to an dynamically created element

I'm using simplescroll bar (SSB), which adds wrappers around my scroll content on page load. And I need to attach an event listener, which would work on scroll.

Without SSB a simple

document.querySelector(".element").parentNode.addEventListener('scroll', handler);

did work. But now it doesn't work, since the right .parentNode doesn't exist yet, it will be added later on by SSB in background (I don't know when, I don't know how and I have no control on it).

How do I attach scroll handler to dynamically created (not by me) element?

With a click event I do use a function like this

function addPostponedEventListener(selector, eventName, handler)
{
    document.addEventListener(
        eventName, 
        e => 
        {
            const el = e.target;
        
            if (el.closest(selector))
            {
                handler();
            }
        }
    )
}
addPostponedEventListener('.element', 'scroll', handler);

but it works only with bubbling, and bubbling seems to be disabled for scroll event, so it doesn't work.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Thanks to this answer I was able to do it:

function addPostponedEventListener(selector, eventName, handler)
{
    let interval = setInterval(() => 
    {
        let el = document.querySelector(selector);
        if (el)
        {
            el.addEventListener(eventName, handler);
            clearInterval(interval);
        }
    }, 100);
}
about 4 years ago · Juan Pablo Isaza 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