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?

Answers:

Answer

i think this may bind your scroll

$('#child').live('keyup', function() {
var el = $(this);
if (!el.data("has-scroll")) {
    el.data("has-scroll", true);
    el.scroll(function(){
       //doscrollaction(el);
    });
}
doscrollaction(el);
});

as requested by op:

i change the css so child overflows and use jquery.scroll and that works, however there is no 'scroll' event like you have for jquery not that i know of anyway, hence the reason why bin, live etc can not be set for scroll and also why your deligate will not work

Answer

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.