0

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.

klm123
  • 12,105
  • 14
  • 57
  • 95

1 Answers1

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);
}
klm123
  • 12,105
  • 14
  • 57
  • 95
  • 1
    MutationObserver sounds great! could you make an answer with it? There is no dependency on jQuery, $ was just a custom 1-line function, i've removed it from my answer, thanks. – klm123 Nov 10 '21 at 08:16
  • @Ouroborus, I don't, I just add ss-container attribute to my scroll panel. It auto innitializes itself. – klm123 Nov 10 '21 at 09:18