Reputation: 23
I am using wordpress to create a website. I was trying to generate a sticky navbar and was successful with following code: --JS:
const nav = document.querySelector('#masthead');
let navTop = nav.offsetTop;
function fixedNav() {
if (window.scrollY >= navTop) {
nav.classList.add('fixed');
} else {
nav.classList.remove('fixed');
}}
window.addEventListener('scroll', fixedNav);
--CSS:
#masthead.fixed {
position: fixed;
box-shadow: 5px 5px 19px 0px rgba(0, 0, 0, 0.5);
}
#masthead.fixed ul li img {
height: 36px;
}
#masthead.fixed ul li a {
font-size: 14px;
}
The css applies to the navbar when the page is scrolled down and sticky function invokes. Now the problem is when I return the webpage to its top the navbar should restore to its previous styling and the css that was applied after the scrolling should release its effect. How can I achieve that?
Thank You.
Upvotes: 0
Views: 47
Reputation: 11
Just add an statement to check when the page is at the top:
else if (scrollY == 0) {
nav.classList.remove('fixed')
}
Also I would recommend to add a boolean variable so the event doesn't fire all the time, something like this:
var ticking = false;
window.onscroll = function (e) {
if (!ticking) {
if (window.scrollY >= navTop) {
nav.classList.add('fixed');
ticking = true;
} else if (scrollY == 0) {
nav.classList.remove('fixed');
ticking = false;
}
Upvotes: 1
Reputation: 84
You just need to leave only "greater" and remove "equals", because it means if scroll position greater OR equals 0, then apply fixed style.
Write it like that: if (window.scrollY > navTop)
Upvotes: 0