I am trying to use jquery delegate to bind to scroll events.
html
<div id='parent'>
<div id='child'>Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah </div>
</div>
css
#parent {
width:200px;
height:200px;
border:2px solid black;
overflow:auto;
}
#child {
width:300px;
height:300px;
background:red;
}
javascript
$('#parent').delegate('#child', 'scroll', function(){
alert(this)
})
jsfiddle
http://jsfiddle.net/C6DRR/1/
Why doesn't it work?
Because scroll event does not bubble. http://www.quirksmode.org/dom/events/scroll.html
why doesn't delegate work for scroll?
Because scroll event doesn't bubble through the DOM.
But, on modern browsers (IE>8), you can capture scroll event to e.g document level or any static container for dynamic element. You have to use javascript addEventListener()
method passing true
as useCapture
parameter, jQuery doesn't support capturing phase:
Note: in your example, scroll
event happen to #parent
level, not #child
document.addEventListener('scroll', function (event) { if (event.target.id === 'parent') { // or any other filtering condition console.log('scrolling', event.target); } }, true /*Capture event*/);
For explanation on difference between event capture/propagation, see here or there.
Be aware, a captured event is always fired before any other bubbling event of same kind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With