Steffi
Steffi

Reputation: 7057

how to determine the number of px scrolled in jquery?

I want to get the value of px when I scroll in jQuery.

For example, at the middle of page, I scroll down a little bit. Here, I want to know how many px I scrolled. (3px, 5px, ..., 10px, 11px ?)

Whatever the position of the scroller.

If my scroller is a 300px from the top. I scrolled 10px. So my scroller is now at 310px. How to get the value I scrolled (here : 10px ?)

Is it possible ?

Upvotes: 1

Views: 1108

Answers (2)

adeneo
adeneo

Reputation: 318182

$(window).on('scroll', function() {
    var distanceScrolled = $(window).scrollTop();
});

EDIT:

using a timer (which is in no way accurate) :

var timer, lastScrolled = 0;

$(window).on('scroll', function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
        $('#test').text('you scrolled '+($(window).scrollTop() - lastScrolled)+' pixels')
        lastScrolled = $(window).scrollTop();
    },400);
});​

FIDDLE

Upvotes: 0

Touki
Touki

Reputation: 7525

Here's a working sample code :

var startScroll,
    toHandler,
    endScroll;

$(window).on("scroll",function(){
    if (!startScroll) {
        startScroll = $(window).scrollTop();
        console.log("Started:" + startScroll);
    } else {
        if (toHandler) {
            clearTimeout(toHandler)
        }
        toHandler = setTimeout(function(){
            endScroll = $(window).scrollTop();
            console.log("Ended :"+endScroll);
            console.log("Scrolled "+(endScroll-startScroll));
            startScroll = 0;
        },200)
    }
});​

http://jsfiddle.net/Touki/jXwAG/

The timeout is needed to prevent the scroll event to fire multiple times and to get incorrect value.

This sample will print how much pixels it moved after 200ms

Upvotes: 1

Related Questions