Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!