Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't delegate work for scroll?

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?

like image 971
Tim Avatar asked Feb 12 '12 23:02

Tim


2 Answers

Because scroll event does not bubble. http://www.quirksmode.org/dom/events/scroll.html

like image 122
user1087079 Avatar answered Sep 22 '22 16:09

user1087079


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*/); 

-DEMO-

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.

like image 26
A. Wolff Avatar answered Sep 25 '22 16:09

A. Wolff