Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery if scroll is a certain amount of pixels

Tags:

jquery

scroll

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');

}
like image 507
Ryan Avatar asked Nov 16 '11 07:11

Ryan


1 Answers

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.

like image 67
Mathias Bynens Avatar answered Nov 15 '22 13:11

Mathias Bynens