I am currently facing an issue with adding a scroll listener to an element that has overflow-y: scroll
If you have a div:
<div id='my-div'>my div</div>
styled like this:
#my-div {
overflow-y: scroll
}
The JavaScript code below will not work when scrolling inside the div:
window
.addEventListener('scroll', function() {
console.log('do something on scroll')
})
This is because scroll events do not bubble for performance reasons.
It is better to directly attach the scroll event like this:
document
.getElementById('my-div')
.addEventListener('scroll', function() {
console.log('do something on scroll')
})
However, passing references to elements in applications can be cumbersome. In my React application (but also applicable to any application following the W3C document spec), there are multiple layers of nesting to access the element with overflow
set. Is there a way to avoid passing references around?