jQuery/JavaScript: Detecting scroll direction - code structure issue

Sven picture Sven · Mar 7, 2013 · Viewed 17.6k times · Source

I need to detect the direction in that a user scrolls - "up" or "down". Based on the code found in this answer: How can I determine the direction of a jQuery scroll event?

I tried to wrap it in a function so it's a bit more differentiated - but unfortunately, it's not working. I think it has something to do with how I return the value, but the direction is always "up". Being fairly new to JavaScript I am having problems solving this issue.

Here is the code:

$(document).ready(function () {

    'use strict';

    var lastScrollTop = 0,
        st,
        direction;

    function detectDirection() {

        st = window.pageYOffset;

        if (st > lastScrollTop) {
            direction = "down";
        } else {
            direction = "up";
        }

        lastScrollTop = st;

        return  direction;

    }

    $(window).bind('scroll', function() {

        detectDirection();
        console.log(detectDirection());

    });

});

And I've also set up a Fiddle.

Could you please help me spotting where the problem is?

Answer

Barmar picture Barmar · Mar 7, 2013
$(window).bind('scroll', function() {

    var dir = detectDirection();
    console.log(dir);

});

You were calling detectDirection() twice during each scroll event. The first one detected the correct direction, but the second one just saw it in the same place, so it returned "up", and that's what you logged.