Im trying to create to nav bar that goes pops up when the users scrolls up and when they reach the end of the page. reference can be the nav bar in Nike website. I wrote the JScript for this, but that doesn't do the work.
const nav = document.querySelector('#navbar');
let topOfNav = nav.offsetTop;
function fixNav() {
if (window.scrollY >= topOfNav) {
document.body.style.paddingTop = nav.offsetHeight 'px';
document.body.classList.add('fixed-nav');
} else {
document.body.style.paddingTop = 0;
document.body.classList.remove('fixed-nav');
}
}
window.addEventListener('scroll', fixNav);
// show nav bar when at the end of the page
window.onscroll = function(ev) {
if ((window.innerHeight window.scrollY) >= document.body.offsetHeight) {
nav.classList.add('show-nav');
} else {
nav.classList.remove('show-nav');
}
};
.sub-menu {
visibility: hidden;
}
<nav>
<ul id="navbar">
<li>
<a href="%">Test</a>
<ul >
<li>
<a href="#">1</a>
</li>
</ul>
</li>
</ul>
</nav>
CodePudding user response:
w3schools has an example on this, check if it works for you: https://www.w3schools.com/howto/howto_js_navbar_sticky.asp
CodePudding user response:
I can see some problems
Use of
querySelectorreturns a static node, which means the position stays fixed all the time and you're runningfixNaveach time with the sametopOfNavwhich means you'll always get the same result, instead, you either query your navbar inside thefixNavor usegetElementsByIdwhich returns live node.Use of
paddingTopinstead ofmarignTop, you're resizing your navbar instead of moving itYour classes do not exist in the css as well, you need to include them if you want me to provide a solution instead of hints, but mostly likely, you didn't position your navbar bar, which means it's static and positioning properties like
topandbottomwon't work on it. Instead, you need to make itrelativefor this to work.
Or just use position: sticky; top: 0; left: 0 and it should stick while scrolling
