I'm using:
$(window).scroll(function(e){
.....
});
How can i find out the number of pixels (and the direction, if absolute number) that were scrolled?
Thanx
To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
If you want to check whether the user has scrolled to the bottom of the page, you can use the scroll() jQuery event. The given code piece takes the top scroll of the window, so how much the page is scrolled down, it adds the height of the visible window and checks if it is equivalent to the height of the document.
If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards.
The scrollLeft() method sets or returns the horizontal scrollbar position for the selected elements. Tip: When the scrollbar is on the far left side, the position is 0. When used to return the position: This method returns the horizontal position of the scrollbar for the FIRST matched element.
Here is one way:
jQuery(function($) {
var lastScroll = document.body.scrollTop;
$(window).scroll(function(e) {
var newScroll = document.body.scrollTop;
console.log(newScroll - lastScroll);
lastScroll = newScroll;
});
});
Use scrollTop to determine what you're looking for.
The line below doesn't work on Firefox 19 (which I updated this year: 2013).
var lastScroll = document.body.scrollTop;
The solution, which will also improve the cross browser compatibility, is to use a jQuery call:
var lastScroll = $(document).scrollTop();
Final result:
$(function(){
var lastScroll = $(document).scrollTop();
$(window).scroll(function(e) {
var newScroll = $(document).scrollTop();
console.log(newScroll - lastScroll);
lastScroll = newScroll;
});
});
Enjoy!
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