hanging navigation bar when scrolling passed js in javascript

Here's an example of how you can implement a sticky navigation bar using JavaScript and CSS. This code listens for when the user has scrolled past a certain point on the page then adds and removes classes from the navigation bar to make it sticky.

<!-- Make sure to have a navigation bar in your HTML -->

<nav id="nav">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>
201 chars
10 lines
/* Add some styles to the navigation bar */
nav {
  background: #333;
  color: white;
  padding: 10px;
}

/* Add a class to make the navigation bar sticky */
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
214 chars
14 lines
index.tsx
// Select the navigation bar
const nav = document.getElementById('nav');

// Get the offset position of the navbar
const sticky = nav.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function scrollHandler() {
  if (window.pageYOffset >= sticky) {
    nav.classList.add('sticky')
  } else {
    nav.classList.remove('sticky');
  }
}

// Add a listener for scrolling
window.addEventListener('scroll', scrollHandler);
504 chars
18 lines

Note: You'll need to modify or adjust nav.offsetTop depending on your layout and styles.

gistlibby LogSnag