3

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.