I am currently working on a project that involves two navbars. The first navbar is dedicated to contact information, while the second navbar contains menu links.
My goal is to have the second navbar fixed at the top of the page when scrolling, and I am looking to achieve this using vanilla JavaScript.
If you'd like to see a live demo, check out the example on codepen.io
Below is a snippet of my full code:
JavaScript, CSS, and HTML:
(function () {
'use strict'
// for Off-Canvas Menu
document.querySelector('[data-bs-toggle="offcanvas"]').addEventListener('click', function () {
document.querySelector('.offcanvas-collapse').classList.toggle('open')
})
})()
@media (max-width: 991.98px) {
.offcanvas-collapse {
position: fixed;
top: 56px; /* Height of navbar */
bottom: 0;
left: 100%;
width: 100%;
padding-right: 1rem;
padding-left: 1rem;
overflow-y: auto;
visibility: hidden;
background-color: #343a40;
transition: transform .3s ease-in-out, visibility .3s ease-in-out;
}
.offcanvas-collapse.open {
visibility: visible;
transform: translateX(-100%);
}
}
<header class="myheader">
<!-- First Navbar -->
<nav class="navbar navbar-dark bg-info">
<div class="container-fluid">
<span class="navbar-brand mb-0 h1">First Navbar</span>
</div>
</nav>
<!-- Second Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse offcanvas-collapse">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">About</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</header>