hanging navbar js in javascript

Here's an example code for creating a hanging navbar using JavaScript:

HTML:

index.tsx
<nav class="navbar">
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Contact</a>
</nav>

<div class="content">
  <h1>Lorem ipsum dolor sit amet</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus id elit nisi. Nulla facilisi.</p>
</div>
273 chars
11 lines

CSS:

index.tsx
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #333;
  overflow: hidden;
  transition: top 0.3s;
}

.navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.navbar a:hover {
  background-color: #ddd;
  color: black;
}

.navbar.sticky {
  top: -50px;
}
369 chars
28 lines

JavaScript:

index.tsx
// Get the navbar
var navbar = document.querySelector('.navbar');

// Get the offset position of the content
var content = document.querySelector('.content');
var offsetPosition = content.offsetTop;

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

// Listen for scroll events
window.addEventListener('scroll', handleScroll);
567 chars
19 lines

This code uses querySelector to get the navbar and the content, and offsetTop to get the offset position of the content. Then, a function named handleScroll is defined that checks if the user has scrolled past the content using window.pageYOffset, and adds or removes the .sticky class accordingly using classList.add and classList.remove. Finally, an event listener is added to the window object that listens for scroll events and calls handleScroll when triggered. This creates a hanging navbar that sticks to the top of the page once the user scrolls past the content.

gistlibby LogSnag