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?