I'm working on a website which has a header that, when the scrollTop()
value is more than 1/4 of the browser's height, animates up and down on and off the screen depending on whether the user is scrolling up or down. For the home page, the header changes background and text color after the said scrollTop()
value to accommodate a video background.
However, the headerScrollEvents()
function, which adds the "show" (header sliding down), "hide" (header sliding up) and "active" (header changing background and text color) classes to #header
when scrolled, is still running when the scroll position number is less than 1/4 of the browser's height. The goal is to prevent those classes from being added once the user scrolls upward from that scrollTop()
value to the very top.
How do I get a jQuery function to trigger or stop upon reaching certain scroll positions?
JS:
function headerScrollEvents() {
var yPos = $(window).scrollTop();
$(window).scroll(function() {
var newYPos = $(this).scrollTop();
if (newYPos > yPos) {
$("#header").removeClass("show active").addClass("hide");
} else {
$("#header").removeClass("hide").addClass("show active");
}
yPos = newYPos;
});
}
$(window).scroll(function() {
if ( $(window).scrollTop() <= $(window).height() / 4 ) {
$("#header").removeAttr("class");
} else if ( $(window).scrollTop() >= $(window).height() / 4 ) {
headerScrollEvents();
}
});
CSS:
#header {
top: 0;
left: 0;
position: fixed;
width: 100%;
z-index: 25;
padding: 48px 0;
transition: transform 500ms ease, background 500ms linear;
background: #000;
}
#header.hide {
transform: translateY(-100%);
}
#header.show {
transform: translateY(0%);
}
#header.active {
background: #fff;
}