BLAZORLOVER
BLAZORLOVER

Reputation: 2011

jQuery 'scroll' not firing

I have the following:

 var onScroll = function () {
        alert('scroll');
 };
 scrollArea = $('body');
 scrollArea.on('scroll', onScroll);

I can do $('body').scrollTop(400) and the body scrolls fine, but the alert is never called when I manually scroll. What could be causing this?

Upvotes: 3

Views: 8927

Answers (2)

Yogesh Mistry
Yogesh Mistry

Reputation: 2152

When you scroll the page, it's window that is scrolling not the body. So change it to $(window).on('scroll', onScroll);

EDIT: If you want to bind it to body specifically you may do it using document.body.onscroll = onScroll;. But make sure you do not bind any onscroll event to window in that case. If you do so, document.body.onscroll will be ignored and window.onscroll will be listened to.

Check this in action at the fiddle link here.

Upvotes: 6

Lupinity Labs
Lupinity Labs

Reputation: 2464

Don't use $('body'), but either $(document) or $(window) to catch the scroll, like this:

$(document).ready(function() {
    $(document).scroll(function() {
    console.log('Scrolled to ' + $(this).scrollTop());
  })
});

Here's a working jsFiddle: https://jsfiddle.net/4rrm3myL/1/

Upvotes: 5

Related Questions