I currently have a navigation that hides as you scroll down and then if you scroll up the navigation appears again.
I also have a class of .fixed
on #top-wrapper
which will change the layout/styling of this div
. However when you get back to the top of the screen (threshold 200px) I want the class .fixed
to be removed. I'm struggling to get it to detect this and then remove the class.
(function () {
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('top-wrapper');
var toggled;
var threshold = 200;
var checkScroll = function () {
curScroll = w.scrollY || doc.scrollTop;
if (curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if (curDirection !== prevDirection) {
toggled = toggleHeader();
}
prevScroll = curScroll;
if (toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function () {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add('hide');
header.classList.add('fixed');
}
else if (curDirection === 1) {
header.classList.remove('hide');
}
else if (curDirection === 1 && curScroll > threshold) {
header.classList.remove('fixed');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();
body {
padding:0;
margin:0;
}
main {
min-height:20000px;
}
h1 {
padding-top:40px;
}
#top-wrapper {
width:100%;
height:50px;
background:red;
position:fixed;
top:0;
transition: all 0.3s ease;
}
#top-wrapper.hide {
top:-50px;
}
#top-wrapper.fixed {
background:blue;
}
<main>
<h1>
IM THE TOP OF THE PAGE
</h1>
<section id="top-wrapper"></section>
</main>