Change the color of the navbar when scrolling using bootstrap and jquery

Using Bootstrap to design a navigation bar, I have two main goals:

  1. I want the navbar to change color when the page is scrolled down by 20%, and then revert back to its original color when scrolling back to the top.

  2. When the collapse feature is active in Bootstrap i.e. when the collapsed div is visible, I need the navbar to maintain its original color regardless of window scroll position.

    <div class="navbar-collapse nav-mobile-collapse collapse show" 
    id="navbarResponsive" style="">

HTML

<nav class="navbar-expand-lg navbar-dark fixed-top d-block d-lg-none">
 <div id="nav-mobile" class="d-flex flex-row nav-flex-row">
    <div class="p-3 mr-auto"><img class="img img-fluid" 
      src="img/png/logo.png" /></div>
  <div class="p-3">
    <span class="navbar-toggler navbar-toggler-right" style="background-
       color:transparent;color:white" data-toggle="collapse"
      data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-
      expanded="false" aria-label="Toggle navigation">
        <i class="fa fa-bars fa-2x" aria-hidden="false" style="color:white">
        </i>
    </span>
  </div>
</div>

<div class="collapse navbar-collapse nav-mobile-collapse" 
  id="navbarResponsive">
  <div id="top-menu"  class="navbar-container collapsebar-main">
    <div style="flex:1" class="">
        <a class="active js-scroll-trigger " href="#about">About</a>
    </div>
    <div style="flex:1">
        <a class="js-scroll-trigger" href="#product">Products</a>
    </div>
    <div style="flex:1">
        <a class="js-scroll-trigger" href="#partners">Partners</a>
    </div>
    <div style="flex:1" class="testimonial-nav">
        <a class="js-scroll-trigger" href="#testimonial">Testimonials</a>
    </div>
  </div>
 </div>
</nav>

JAVASCRIPT

$(window).scroll(function(){

  document.getElementById('nav-mobile').style.webkitTransition = 'opacity
    1s';
  document.getElementById('nav-mobile').style.mozTransition = 'opacity 1s';

  var windowpos = $(window).scrollTop();

  $('#navbarResponsive')
   .on('shown.bs.collapse', function() {
   document.getElementById('nav-mobile').style.backgroundColor = '#1c223f';
  });

  .on('hidden.bs.collapse', function() {
    if (windowpos > 50) {
      document.getElementById('nav-mobile').style.backgroundColor =
         '#1c223f';
    }
    else {
      document.getElementById('nav-mobile').style.backgroundColor =
         'TRANSPARENT';
    }
  });

 if (windowpos > 50) {
    document.getElementById('nav-mobile').style.backgroundColor = '#1c223f';
  }  
});

Answer №1

It is recommended to move the code snippet $('#navbarResponsive') out of the scroll function as it will only be initialized when the window is scrolling.

I made some changes and here is a demo of the updated version:

$(window).scroll(function() {

  document.getElementById('nav-mobile').style.webkitTransition = 'opacity 1s';
  document.getElementById('nav-mobile').style.mozTransition = 'opacity 1s';

  var windowpos = $(window).scrollTop();

  if (windowpos > 50 || $("#navbarResponsive").hasClass("show")) {
    document.getElementById('nav-mobile').style.backgroundColor = '#1c223f';
  } else {
    document.getElementById('nav-mobile').style.backgroundColor = '';
  }
});

$('#navbarResponsive')
  .on('shown.bs.collapse', function() {
    document.getElementById('nav-mobile').style.backgroundColor = '#1c223f';
  }).on('hidden.bs.collapse', function() {
  var windowpos = $(window).scrollTop();
    if (windowpos > 50) {
      document.getElementById('nav-mobile').style.backgroundColor =
        '#1c223f';
    } else {
      document.getElementById('nav-mobile').style.backgroundColor =
        '';
    }
  });
body {
  height: 1000px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<nav class="navbar-expand-lg navbar-dark fixed-top d-block d-lg-none">
  <div id="nav-mobile" class=" d-flex flex-row nav-flex-row">
    <div class="p-3 mr-auto"><img class="img img-fluid" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVCT-lYaIPfWsXbMZpFleT5-m-lA4Qbs9YhG44nDGAw7XEYjqB" /></div>
    <div class="p-3">

      <span class="navbar-toggler navbar-toggler-right" style="background- 
       color:transparent;color:white" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria- expanded="false" aria-label="Toggle navigation">
        <i class="fa fa-bars fa-2x" aria-hidden="false" style="color:white"> 
        </i>
    </span>
    </div>
  </div>
  <div class="collapse navbar-collapse nav-mobile-collapse" id="navbarResponsive">
    <div id="top-menu" class="navbar-container collapsebar-main">
      <div style="flex:1" class="">
        <a class="active js-scroll-trigger " href="#about">About</a>
      </div>
      <div style="flex:1">
        <a class=" js-scroll-trigger" href="#product">Products</a>
      </div>
      <div style="flex:1">
        <a class=" js-scroll-trigger" href="#partners">Partners</a>
      </div>
      <div style="flex:1" class="testimonial-nav">
        <a class=" js-scroll-trigger" href="#testimonial">Testimonials</a>
      </div>
    </div>
  </div>
</nav>

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

Replicating a row in a table without disrupting a button within the row

As a novice in the world of coding, I am currently embarking on a project to revamp an existing website. The task at hand involves creating a table with a built-in save/edit feature, which I have successfully implemented. However, I am facing a roadblock w ...

What is the best way to upload a local image using JavaScript for TensorFlow?

I am having trouble loading a data.jpg file to be used by tensorflow mobilenet. When I try to require the file normally, I encounter an error message: So, my question is how can I load an image in my JavaScript code for use? I have tried various methods of ...

The output is generated by React useContext with a delay

When using the data obtained from useContext to verify if the logged-in user is an Admin, there seems to be a delay where it initially returns "undefined" and then after about 5 seconds, it provides the actual value. This causes the code to break since it ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

React Material UI Select component is failing to recognize scrolling event

Having some difficulty understanding how to detect a scroll event with a Select component using Material-UI. The Select has MenuProps={...}, and I want to listen for the scroll event inside it. I've tried putting onScroll within MenuProps={...}, but ...

Extension for Chrome that enhances YouTube video playback experience

I'm struggling to figure out why this isn't functioning. I've reviewed the Google extension dev docs and examined some sample code. Checked various Stack Overflow questions and answers, but haven't received any helpful feedback or res ...

What is the best way to create a mapping function in JavaScript/TypeScript that accepts multiple dynamic variables as parameters?

Explaining my current situation might be a bit challenging. Essentially, I'm utilizing AWS Dynamodb to execute queries and aiming to present them in a chart using NGX-Charts in Angular4. The data that needs to appear in the chart should follow this fo ...

The standard date format used in Javascript/Jquery programs

I have a kendo date picker set to display dates in the format "MM/dd/yyyy". I need to use jquery or javascript to ensure that the selected date is not in the future and is greater than '01/01/1900'. The problem I'm encountering is handling ...

"Redirecting visitors based on their location using GeoIP targeting for

Is there a way to implement a code that redirects users based on their location? For example, if a user accesses the site from the United Kingdom, they should be redirected to /UK/, if from the US to /US/, and if from anywhere in the EU (excluding the UK) ...

Transforming the add to cart button into a view button within the product listings: an easy guide

I am currently developing a unique ecommerce website called bookslab.in. To enhance the user experience, I would like to replace the "add to cart" button with a "view details" button when users view the list of available products. Furthermore, when users c ...

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

Using jQuery, you can dynamically fill a field with data retrieved from two separate fields

Is there a way to automatically populate the 'Full Name' field based on what the user enters in the 'First Name' and 'Last Name' fields? For example, if the user types 'John' and 'Smith', the 'Full Nam ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...

The Materialize accordion feature seems to be incompatible with the Algolia template

I'm currently facing an issue where the product description using Algolia in a Materialize accordion does not trigger when clicked. Below is the code snippet from my view: <div class="row"> <div id="hits-container"></div> ...

How come the Google fonts won't display correctly within my HTML document?

After importing some fonts into my CSS file, I noticed that they are not displaying correctly in the design. Below is the code for the imported fonts and CSS linking: https://i.stack.imgur.com/9RQ4u.png The output only shows sans-sarif working properly: ...

Analyzing HTML markup to locate an anchor tag

While attempting to parse an HTML code using BeautifulSoup in order to retrieve a link that is hidden and does not appear on the website, I have encountered difficulties as it only retrieves links visible on the page. Is there a method to effectively par ...

What is the procedure for inserting comments into inline CSS?

You know, I've been wondering how to effectively comment out inline CSS styles within HTML tags. Is it best to use the /* */ comments from CSS? Or should we opt for <!-- --> in HTML? <span class="color_dark" style="top:20px;font-size: 17px;l ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

The process of combining identical data values within an array of objects

Can anyone help me with merging arrays in JavaScript? Here is an example array: [{ "team": team1, "groupname": "group1", "emp-data": [{ "id": 1, "name": "name1", }], }, { "team": team1, "groupname": "group1", " ...

Designing links within a web application

Currently, I am developing a web application that will contain a high volume of clickable elements. The challenge lies in maintaining a visually appealing design while adhering to web best practices such as using different colors and underlines for links. ...