Jquery if scroll is a certain amount of pixels

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.

Leave a Comment

techhipbettruvabetnorabahisbahis forumu