Question: My goal is to create a specific animation on my website. When loading the page on mobile, I want to display the div with ID "sub-header", but once the user scrolls more than 50px down, I want to hide it. Additionally, if the user scrolls up by 60px at any point while on the page, I want to show sub-header again.
The Issue I am Facing: The menu hides as expected when scrolling down, but when scrolling back up, it repeatedly shows and hides multiple times.
JQuery Code:
var newScroll = 0;
var subHeaderPosition = true;
var currentScroll = 0;
$(window).scroll(function () {
currentScroll = $(window).scrollTop();
if ($(window).width() < 779) {
if (currentScroll > 50 && subHeaderPosition) {
console.log("Current Scroll position: " + currentScroll);
console.log("Hiding Sub-Header");
$("#sub-header").hide(300);
subHeaderPosition = false;
newScroll = $(window).scrollTop();
console.log("New Scroll position: " + newScroll);
} else if ((currentScroll - 60) < newScroll && !subHeaderPosition) {
console.log("Scroll position: " + currentScroll);
console.log("Showing Sub-Header");
$("#sub-header").show(300);
subHeaderPosition = true;
newScroll = $(window).scrollTop();
} else {
newScroll = $(window).scrollTop();
}
}
});
UPDATE: Upon further investigation, I noticed that 'newScroll' and 'currentScroll' always have the same value, which gives me some insight into where the problem might lie. I will share a solution once I find one, but I'm open to suggestions from others as well.