Implementing a sticky second Navbar with Bootstrap 5 and Vanilla JavaScript to stay fixed at the top during scrolling

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>

Answer №1

Your navigation is enclosed within the header section. Consider implementing the following code snippet:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Fullscreen OwlCarousel2 with centered Bootstrap Tab.</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceaca1a1babdbabcafbe8efbe0fee0fee3acabbaafff">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<!-- 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="#">Second 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-light" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>

<main class="container py-5">

<h1>What is Lorem Ipsum?</h1>

<p class="lead">
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>

... (additional repeated content) ...

</main>


<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9895958e898e889b8abacfd4cad4cad7989f8e9bcb">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

dojo.xhrGet evaluating script tags

I have a piece of code that is similar to the following: var targetElem = dojo.byId('xyz'); var xhrArgs = { url: 'Welcome.do?call=JS', preventCache: true, load: function(data){ targetElem.innerHTML = data; dojo.parser.par ...

JavaScript failed to execute

I am trying to make the JavaScript function execute when the subcat-tab class is clicked, but for some reason it's not working. There are no error messages showing up, but nothing is happening. This is within a phtml file in Magento 2. <a href=&qu ...

Implementing a gradient effect on a specific image element within an HTML canvas with the help of jQuery

Currently, I'm working on an HTML canvas project where users can drop images onto the canvas. I am looking to implement a linear gradient effect specifically on the selected portion of the image. My goal is to allow users to use their mouse to select ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Invoke actions when clicking outside of components

Currently, I have a HeaderSubmenu component that is designed to show/hide a drop-down menu when a specific button is clicked. However, I am now trying to implement a solution where if the user clicks anywhere else in the application other than on this drop ...

Leverage the power of Vue Nuxt Auth to activate authentication middleware on a route-by-route

Is there a way to implement auth middleware for individual routes using Class Components? How can I achieve the same functionality as this: <script> export default { middleware: 'auth' } </script> The following method does n ...

Minimizing the Height of HTML Table Rows

I have a table with a few rows. I'm trying to set the height of the 1st and 3rd rows to 1px and keep the 2nd row at normal height. However, my code isn't working as expected. Here is the HTML CODE: <table border="0"> <tr style="hei ...

Issue with Ckeditor inside a bootstrap modal

I am encountering an issue while trying to integrate ckeditor into a bootstrap modal. Whenever I attempt to use it, the functionality does not work as expected. Clicking on any icons triggers an error in the console stating Uncaught TypeError: Cannot rea ...

Node.js - Locate a specific parameter within an array that is nested within a JSON object, and retrieve the remaining

I am working with a Node.js API call that returns a JSON object. My goal is to extract the customer's phone number from this object using a specific function, like body.result.reservations[X of reserv.].client.phone, and retrieve parameters such as p ...

Utilizing jQuery to apply a class to an element and modify the CSS parameters with custom values simultaneously

Unsure if this idea is feasible, but I'll attempt to explain my requirements. I am interested in accomplishing something like the following: A CSS class with variables X, Y, and Z left undefined: .r {border-radius:Xpx;-webkit-border-radius:Ypx;-moz ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

What is the best way to incorporate material-ui icons into my project?

I'm trying to incorporate an icon inside an IconButton, like so: <IconButton > <SearchIcon/> </IconButton> After adding @material-ui/icons to my package.json file and importing the necessary components: import IconButton from ...

I require my two elements to possess opposing transformations in their coordinates or directions to enable dragging capabilities

Changing the code to move the elements in opposite directions is my goal. I attempted multiplying the second element by -1, but unfortunately, I keep ending up with a NAN or undefined result. Any suggestions on how to achieve the desired effect? ...

Encountering the error of receiving "$ undefined," despite making a reference to the library

I have included the JQuery library in the following way: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> Despite trying to download the library and include it locally in my project, I ...

Javascript keycode used to target the element when a key is pressed

In my current project, I am utilizing a code snippet to attach a KeyDown event handler to any element within the HTML form. for(var i=0;i<ele.length;i++) { ele[i].onkeydown = function() { alert('onkeydown'); } } I am ...

Why is it that one function does not hold off on execution until Promise.all() is resolved in another function?

I am currently working on a form that allows users to upload files seamlessly. <form @submit.prevent="sendForm" enctype="multipart/form-data"> <input multiple ref="PostFiles" name="PostFiles" type="file" @change="selectFile('add')"> ...

Leveraging HTML tables for input purposes

Just starting out with php, HTML, and mysql. Using HTML tables for the first time here. Created an HTML table filled with data from a MySQL table. Planning to use this table as a menu where users can click on a cell with a specific date. The clicked date ...

Ways to collapse all rows that are expanded except the one that is currently open in iView Tables

Utilizing iView Tables to display data in a table with an expand option. As of now, when clicking on the expand button for a row, the row expands but previously expanded rows do not collapse, causing all expanded rows to be visible at once. Is there a wa ...

Enhancing Angular 4 classes with dependency injection techniques

Currently utilizing angular 4 and angular cli for my project development. I have created some classes that serve as the base for my components! However, as the constructors of these classes grow during development, I find myself in a phase where I need to ...

How can states be passed down as props in React?

This might be a beginner question, but I've been struggling with it all day. Any help would be appreciated. Apologies for the length, I just wanted to explain everything I'm having trouble with I am attempting to create custom buttons by build ...