I want to detect whether I am scrolling up or down. I also have a global variable which should be true
if scrolling down and false
if up.
The problem is, if I scroll down once, and keep scrolling down, the console logs true
and down
, but if I then scroll up just once, it logs 'up' correctly but also true
instead of false
. Same goes when scrolling the other way around.
So basically the down
variable is wrong after first scroll change which changes direction.
<div id="id0" data-id="0" class="nbhd red scrolledto"></div>
<div id="id1" data-id="1" class="nbhd yellow"></div>
<div id="id2" data-id="2" class="nbhd green"></div>
<div id="id3" data-id="3" class="nbhd blue"></div>
var down = true;
function setHeights() {
$('.nbhd').css('height', window.innerHeight);
}
function scrollDirection() {
var lastScrollTop = $(window).scrollTop();
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop){
// down
down = true;
console.log('down');
} else if (st < lastScrollTop) {
// up
down = false;
console.log('up');
}
lastScrollTop = st;
});
console.log(down);
}
setHeights();
$( window ).on( "scroll", function() {
scrollDirection();
});
fiddle: https://jsfiddle.net/gh3cgrqL/