Create a sleek and dynamic navbar effect with Bootstrap 5 by easily hiding or showing it after scrolling

Is there a way to make the Bootstrap navbar hide after scrolling for 300px?

I found a code snippet here that hides the navbar on scroll, but it hides immediately. How can I modify it to hide only after scrolling 300px?

HTML:

<nav class="autohide navbar navbar-expand-lg navbar-dark bg-primary">
 <div class="container-fluid">
   <a class="navbar-brand" href="#">Brand</a>
   <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
      <span class="navbar-toggler-icon"></span>
   </button>
  <div class="collapse navbar-collapse" id="main_nav">
    <ul class="navbar-nav ms-auto">
    <li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
    <li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
    <li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
    </ul>
  </div> <!-- navbar-collapse.// -->
 </div> <!-- container-fluid.// -->
</nav>

Javascript:

document.addEventListener("DOMContentLoaded", function(){

  el_autohide = document.querySelector('.autohide');
  
  // add padding-top to bady (if necessary)
  navbar_height = document.querySelector('.navbar').offsetHeight;
  document.body.style.paddingTop = navbar_height + 'px';

  if(el_autohide){
    var last_scroll_top = 0;
    window.addEventListener('scroll', function() {
          let scroll_top = window.scrollY;
         if(scroll_top < last_scroll_top) {
              el_autohide.classList.remove('scrolled-down');
              el_autohide.classList.add('scrolled-up');
          }
          else {
              el_autohide.classList.remove('scrolled-up');
              el_autohide.classList.add('scrolled-down');
          }
          last_scroll_top = scroll_top;
    }); 
    // window.addEventListener
  }
  // if

}); 
// DOMContentLoaded  end

CSS:

.scrolled-down{
  transform:translateY(-100%); transition: all 0.3s ease-in-out;
}
.scrolled-up{
  transform:translateY(0); transition: all 0.3s ease-in-out;
}

Answer №1

Hey there! To tackle this issue, try adjusting the if conditional(scroll_top < 300). By fixing the navigation bar in place and adding a margin top to the main content equal to the navigation bar's height, you can enhance the overall appearance.

Take a closer look at the code snippet below for a more thorough understanding.

document.addEventListener("DOMContentLoaded", function(){

  el_autohide = document.querySelector('.autohide');
  
  // add padding-top to bady (if necessary)
  //el_autohide.style="position: fix;top:0;"

  if(el_autohide){
    var last_scroll_top = 0;
    window.addEventListener('scroll', function() {
          let scroll_top = window.scrollY;
          //console.log(scroll_top > 300)
         if(scroll_top < 300) {
              el_autohide.classList.remove('scrolled-down');
              el_autohide.classList.add('scrolled-up');
          }
          else {
              el_autohide.classList.remove('scrolled-up');
              el_autohide.classList.add('scrolled-down');
          }
          last_scroll_top = scroll_top;
    }); 
    // window.addEventListener
  }
  // if

}); 
// DOMContentLoaded  end
.scrolled-down{
  transform:translateY(-100%); transition: all 0.3s ease-in-out;
}
.scrolled-up{
  transform:translateY(0); transition: all 0.3s ease-in-out;
}

.autohide{
    position: fixed !important;
    top: 0;
    width:100%;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7fafae1e6e1e7f4e5d5a0bba5bba7">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<nav class="autohide navbar navbar-expand-lg navbar-dark bg-primary">
 <div class="container-fluid">
   <a class="navbar-brand" href="#">Brand</a>
   <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
      <span class="navbar-toggler-icon"></span>
   </button>
  <div class="collapse navbar-collapse" id="main_nav">
    <ul class="navbar-nav ms-auto">
    <li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
    <li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
    <li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
    </ul>
  </div> <!-- navbar-collapse.// -->
 </div> <!-- container-fluid.// -->
</nav>

<p style="margin-top: 100px">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore... (remaining content omitted for brevity)

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

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

displaying a div as a pop-up within an ASP.NET MVC 4 web application

One aspect of my asp.net MVC 4 application involves a partial view structured like so: <form class="qty-add" action="#" method="POST"> <label>Qty:</label> <div class="inp-controller"> <a href="#" c ...

Why are my basic style properties not appearing correctly when I use json_encode on an array?

My calendar is written in Javascript within a table with the ID "calendario," allowing me to manipulate it using calendario.rows[i].cells[i]. This calendar lets users make reservations and provides an option to close a day if there are too many reservatio ...

Conceal the HTML input element until the JavaScript has finished loading

Currently, I am using a JQuery plugin to style a form input with type 'file'. The plugin adds a new span over the input element to create a mask effect and encloses everything in a div. However, there is an issue where the standard HTML input box ...

The tweet button feature does not give users the ability to make changes to the content

When using the "Tweet Button" feature, users will follow these steps: The user clicks on the Tweet Button If not already logged in, the user is prompted to login to their Twitter account. New users can also create an account at this stage. The Shar ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

Excessive use of Bootstrap styling causing icons to appear oversized on the webpage

Recently, I embarked on a journey with Electron and React. My goal is to incorporate Font Awesome Icons into my project, but I'm encountering some difficulties. When attempting to render an icon, combining it with the Bootstrap 'row' class r ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

Spinning a 3-dimensional vector in THREE.js using dual axes

Apologies for potentially posting a duplicate question. I am working with two 3D vectors: Center: (0, 0, 0) Orb: (0, 0, 100) My goal is to rotate the orb-vector around the center-vector on both the X and Y axes to ensure an object is always in view of ...

Developing an uncomplicated Angular promise following the invocation of a service

Delving into the realm of Angular promises for the first time, I'm determined to grasp its concepts. In my MainController, I have a simple authentication process using myAuthSrv.authUser with a username and password. Upon successful authentication (. ...

Pinterest-style Angular-UI-Router modal

I am currently working on an app that features a gallery showcasing similar functionalities to . In Pinterest, clicking on a pin displays the pin page above the existing gallery without any information about the background gallery shown in the URL. Users c ...

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...

Changing HTML tags programmatically in Angular while inheriting a template

In my project, I have a Component called DataGrid that represents a table with expandable rows. Each row can be expanded to show a child DataGrid table, which is similar to the parent DataGrid component. To simplify this setup, I created a base class DataG ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

Tips for formatting text in a way that allows it to flow down a page smoothly as the

Working within a CSS Grid setup, I have an image on the left and a block of text on the right. As I reduce the page width, both the image and text resize accordingly to fit the page width. However, once the width goes below 475px, the layout breaks and the ...

What is causing these headers for the children not to center properly?

I am trying to centrally align both vertically and horizontally the <div> element, with its child elements <h1> and <h2> being horizontally centered in relation to the parent <div>. To achieve this, I have created a specific class f ...

Select an option within a for loop nested in an each function

How To Fetch JSON Data and Create a Shopping Cart $.ajax({ url: "myurl", type: 'POST', dataType: "json" }).done(function(response){ $.each(response,function(k,v){ //UL this products info list ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...