Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery Scroll event in $(window), find out the position difference

Tags:

jquery

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

like image 869
André Alçada Padez Avatar asked Jun 18 '11 21:06

André Alçada Padez


People also ask

How do you get the scroll position element?

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.

How can check scroll bottom in jQuery?

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.

How do you know if scroll is up or down?

If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards.

How can get horizontal scroll position in jQuery?

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.


3 Answers

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;
    });
});
like image 131
Mark Eirich Avatar answered Nov 15 '22 06:11

Mark Eirich


Use scrollTop to determine what you're looking for.

like image 36
kinakuta Avatar answered Nov 15 '22 07:11

kinakuta


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!

like image 42
Fabio Nolasco Avatar answered Nov 15 '22 07:11

Fabio Nolasco