Home > Back-end >  Sticky navbar using javascript
Sticky navbar using javascript

Time:01-08

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 querySelector returns a static node, which means the position stays fixed all the time and you're running fixNav each time with the same topOfNav which means you'll always get the same result, instead, you either query your navbar inside the fixNav or use getElementsById which returns live node.

  • Use of paddingTop instead of marignTop, you're resizing your navbar instead of moving it

  • Your 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 top and bottom won't work on it. Instead, you need to make it relative for this to work.

Or just use position: sticky; top: 0; left: 0 and it should stick while scrolling

  • Related