JD Graffam
JD Graffam

Reputation: 11675

How can you use jQuery measure how far down the user has scrolled?

I need to change the style of an element after the user has scrolled down beyond a certain number of pixels, and then change it back once the user has scrolled back up. I'm using jQuery already so I'd like to use jQuery if possible. Can anyone provide an example where you add a a classname to a div once the user has scrolled beyond 200 pixels and then remove the classname once the user has scrolled back up to less than 200 pixels?

Upvotes: 7

Views: 8932

Answers (2)

William Howley
William Howley

Reputation: 493

This is not working, because mobile phones do not accept .scrollTop() since they use a viewport instead. Thus .scrollTop() will always be 0 on mobile phones. Still looking for the right solution to this, but have not found one.

Upvotes: 0

karim79
karim79

Reputation: 342635

See scrollTop, scrollLeft and Events/Scroll.

Example:

$('div#something').scroll(function () {
    if ($(this).scrollTop() > 200) {
        $(this).addClass('foo');
    } else {
        $(this).removeClass('foo');
    }
});

Upvotes: 15

Related Questions