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');
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With