Is there any difference between those two?
$(window).on('scroll', function() { /**/ });
and
$(document).on('scroll', function() { /**/ });
The reason I'm asking is that I've noticed that if I have 2 handlers (one listening on window and the second on document) and at some point I will return false; in the document one, the window handler stops firing, even if the event is namespaced.
You can see the behavior here. After you scroll beyond 300px from the top, the window handler's count doesn't increase anymore.
If I change the window selector to document, the conflict doesn't occur.
And the Fiddle code:
HTML
<div class="fixed">
<div>document scroll event: <span class="scroll1">0</span></div>
<div>window scroll event: <span class="scroll2">0</span></div>
</div>
CSS
body {
height: 3000px;
}
.fixed {
position: fixed;
top: 20px;
left: 20px;
}
JS
$(function () {
var $scroll1 = $('.scroll1');
var $scroll2 = $('.scroll2');
function updateCount($el) {
$el.text(parseInt($el.text(), 10) + 1);
}
$(document).on('scroll', function () {
updateCount($scroll1);
if ($(this).scrollTop() > 300) {
return false;
}
});
$(window).on('scroll', function () {
updateCount($scroll2);
});
});
Events bubble
what you have is
window
|
v
document
|
v
body
This is how the events are handled
- user scrolls on body
- Event scroll is triggered on
bodycheck event handlers
3.1. if any event handler onbodyreturns false stop here
3.2. if no event handlers registered or all event handlers return true, null or undefined pass scroll event to parent(document, goto step 4)Event scroll is triggered on
documentcheck event handlers
5.1. if any event handler ondocumentreturns false stop here
5.2. if no event handlers registered or all event handlers return true, null or undefined pass scroll event to parent(window goto step 6)Event scroll is triggered on
window- check event handlers
7.1. if any event handler onwindowreturns false stop here
7.2. if no event handlers registered or all event handlers return true, null or undefined call other event handlers that come after this one.
You can see where the break points are at #.1
If any of those return false the entire bubble sequense is halted. it's like an emergency brake on a train. Not only your cart stops where you are scoped/positioned, but the entire train stops.
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