Reputation: 189
I have a simple little function that adds / removes classes from an element based on the scroll position and direction.
Everything was working fine, until I added the delay when adding the scrolled
class. Now the final .removeClass('scrolled')
seems to have stopped working.
Does anyone have any ideas why this might be?
This is my code;
$(function () {
var position = $(window).scrollTop(),
$burger = $('.navToggle');
$(window).scroll(function () {
if ( $(document).scrollTop() >= 125 ){
var scroll = $(window).scrollTop();
$burger.delay(325).queue(function(next){
$(this).addClass('scrolled');
next();
});
if (scroll > position) {
$burger.removeClass('going-up up-top').addClass('going-down');
console.log('moving DOWN the page');
} else {
$burger.removeClass('going-down').addClass('going-up');
console.log('moving UP the page');
}
position = scroll;
} else if ( $(document).scrollTop() == 0 ) {
$burger.addClass('up-top').removeClass('scrolled');
}
}); // scroll function
}); // entire function
Edit : As requested, I have created a very simple fiddle https://jsfiddle.net/c5d7r0xq/
In the fiddle, the box starts out with a red background. Once the window has scrolled past 125px this changes to green. It should remain green until the window is scrolled to the very top, where it should go back to red. It does briefly switch to red, but then immediately reverts back to green. This is a very simplified example of what I am working on, but follows the same principle.
Upvotes: 0
Views: 449
Reputation: 92893
The problem is simply that you're delay
ing the addClass('scrolled')
until after the removeClass('scrolled')
has executed. (If I scroll back to the top slowly, the problem doesn't manifest.)
To fix, either queue the removeClass('scrolled')
as well, or remove the addClass('scrolled')
delay entirely.
https://jsfiddle.net/mblase75/c5d7r0xq/4/
} else if ( $(document).scrollTop() == 0 ) {
$burger.addClass('up-top').queue(function(next){
$(this).removeClass('scrolled');
next();
});
}
Upvotes: 1