31

Is there a built in jQuery function to determine the length of a scroll?

I'm trying to write a function that will add a class to a div if the user has scrolled 50 pixels from the top.

So the code will look like this:

if(userHasScrolled) {
     $('#myDiv').addClass('hasScrolled');

}

1 Answer 1

59

You can check $(document).scrollTop() inside of a scroll handler:

var $document = $(document),
    $element = $('#some-element'),
    className = 'hasScrolled';

$document.scroll(function() {
  if ($document.scrollTop() >= 50) {
    // user scrolled 50 pixels or more;
    // do stuff
    $element.addClass(className);
  } else {
    $element.removeClass(className);
  }
});

If adding the class name is all you want (no other actions needed), this could be shortened to:

var $document = $(document),
    $element = $('#some-element'),
    className = 'hasScrolled';

$document.scroll(function() {
  $element.toggleClass(className, $document.scrollTop() >= 50);
});

See http://api.jquery.com/scrollTop/.

Note that it is very inefficient to use scroll event handlers.

3
  • 5
    In this case I like to use the toggleClass method for brevity: $element.toggleClass(className, $document.scrollTop() >= 50);
    – Geert
    Commented Nov 16, 2011 at 8:22
  • 2
    @Geert If adding the class name is all you want, that’s indeed the most elegant solution! Commented Nov 16, 2011 at 8:27
  • Above Solution is not working properly for iOS devices, event is getting fired only after scroll stop.
    – Nitish
    Commented Mar 16, 2017 at 19:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.