The background color of the Bootstrap 5 navbar remains static and does not transition when scrolling

I'm currently developing an Angular application using Bootstrap 5. One of the features I am working on is a transparent navbar that should change to a dark color when the page is scrolled. However, I seem to be encountering an issue where the navbar remains transparent instead of changing color as intended when the page is scrolled.

Here is my code for the navbar:

<nav class="navbar fixed-top navbar-expand-lg navbar-dark p-md-3">
  <div class="container-fluid">
    <a href="#" class="navbar-brand">WorkonPro</a>
    <button
      type="button"
      class="navbar-toggler"
      data-bs-target="#navbarNav"
      data-bs-toggle="collapse"
      aria-controls="navbarNav"
      aria-expanded="false"
      aria-label="Toggle Navbar"
    >
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarNav">
      <div class="mx-auto"></div>
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active item-space" href="#" aria-current="page"
            >Home</a
          >
        </li>
        <li class="nav-item">
          <a class="nav-link item-space" href="#">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link item-space" href="#"> Healthcare </a>
        </li>
        <li class="nav-item">
          <a class="nav-link item-space" href="#">Tech</a>
        </li>
        <li class="nav-item">
          <a
            href="#"
            class="nav-link btn btn-sm item-space grey-button"
            style="color: #fff"
            role="button"
            >Login
          </a>
        </li>
        <li class="nav-item">
          <a
            href="#"
            class="nav-link btn btn-sm item-space green-button"
            style="color: #fff"
            role="button"
            ><strong>Create account</strong>
          </a>
        </li>
      </ul>
    </div>
  </div>
</nav>

Below is the JavaScript code I wrote in an attempt to achieve the desired effect (please note that it corresponds to the body of my HTML page):

<script src="../../../../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
  var nav = document.querySelector('nav');
  window.addEventListener('scroll', function() {
    if (window.pageYOffset > 100) {
      nav.classList.add('bg-dark', 'shadow');
    } else {
      nav.classList.remove('bg-dark', 'shadow');
    }
  });
</script>

Additionally, here is the CSS styling related to the navbar:

.bg-dark {
  background-color: #101011 !important;
}

.navbar-dark .navbar-brand {
  padding: 20px 0 10px 10px;
  color: #fff;
}
.navbar-nav .nav-link {
  color: #101011;
}
.navbar-dark .navbar-nav .nav-link {
  color: rgba(255, 255, 255, 1);
}
.navbar-dark .navbar-brand {
   margin: 0;
   width: 50%;
   float: left;
   display: inherit;
}
.navbar-brand {
  color: #101011;
  padding: 20px 0 10px 10px;
}

body .navbar {
  padding: 6px 0 !important;
}

body .navbar-brand {
  background: none;
}

If anyone could point out what I may be missing or doing wrong and provide a solution, I would greatly appreciate it.

Thank you in advance.

Answer №1

My code worked perfectly for me! Make sure to check the height of your body, as a body height greater than 100vh + 100px is required to run your JavaScript due to the specified condition. Although it's exactly your code, it worked well for me.

<!DOCTYPE html>
<html>
<head>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcdc0c0dbdcdbddcedfef9a819f819d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <style>
    .bg-dark {
      background-color: #101011 !important;
    }

    .navbar-dark .navbar-brand {
      padding: 20px 0 10px 10px;
      color: #fff;
    }
    .navbar-nav .nav-link {
      color: #101011;
    }
    .navbar-dark .navbar-nav .nav-link {
      color: rgba(255, 255, 255, 1);
    }
    .navbar-dark .navbar-brand {
       margin: 0;
       width: 50%;
       float: left;
       display: inherit;
    }
    .navbar-brand {
      color: #101011;
      padding: 20px 0 10px 10px;
    }

    body .navbar {
      padding: 6px 0 !important;
    }

    body .navbar-brand {
      background: none;
    }
  </style>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

<body style=height:120vh class="bg-info">

<nav class="navbar fixed-top navbar-expand-lg navbar-dark p-md-3">
  <div class="container-fluid">
    <a href="#" class="navbar-brand">WorkonPro</a>
    <button
      type="button"
      class="navbar-toggler"
      data-bs-target="#navbarNav"
      data-bs-toggle="collapse"
      arial-controls="navbarNav"
      aria-expanded="false"
      aria-label="Toggle Navbar"
    >
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarNav">
      <div class="mx-auto"></div>
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active item-space" href="#" aria-current="page"
            >Home</a
          >
        </li>
        <li class="nav-item">
          <a class="nav-link item-space" href="#">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link item-space" href="#"> Healthcare </a>
        </li>
        <li class="nav-item">
          <a class="nav-link item-space" href="#">Tech</a>
        </li>
        <li class="nav-item">
          <a
            href="#"
            class="nav-link btn btn-sm item-space grey-button"
            style="color: #fff"
            role="button"
            >Login
          </a>
        </li>
        <li class="nav-item">
          <a
            href="#"
            class="nav-link btn btn-sm item-space green-button"
            style="color: #fff"
            role="button"
            ><strong>Create account</strong>
          </a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e5e8e8f3f4f3f5e6f7c7b2a9b7a9b5">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<!-- <script src="js/jquery-3.6.0.min.js" charset="utf-8"></script> -->
<script>
  var nav = document.querySelector('nav');
  window.addEventListener('scroll', function() {
    if (window.pageYOffset > 100) {
      nav.classList.add('bg-dark', 'shadow');
    } else {
      nav.classList.remove('bg-dark', 'shadow');
    }
  });
</script>

Simply copy and paste this code!

Answer №2

To implement a color change on your navbar based on scroll, simply assign an id to your navbar and insert the following code:

// Customize navbar color on scroll
const myNavbar = document.getElementById("myNavbar");
window.onscroll = (e) => {
 if (window.scrollY > 100) {
 myNavbar.classList.replace("navTransparent", "navColored");
 } else {
 myNavbar.classList.replace("navColored", "navTransparent");
 }};

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

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

The inclusion of Jquery Mobile causes CSS to malfunction

After integrating jQuery Mobile into my HTML via a CDN, I noticed that it completely overrides my styles and disrupts my design. <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" /> <script src="http:// ...

When utilizing express-formidable to retrieve multipart data, it causes basic post requests with request body to hang indefinitely

app.js const express = require('express') const app = express() const appInstance = express() const PORT = process.env.SERVER_PORT || 8080 app.use(express.json()) app.use(express.urlencoded({ extended : true })) app.use(formidableMiddleware ...

Setting up Angular 4 with TailwindCSS

Can TailwindCSS be configured with Angular (4+)? I am willing to eject the Angular project in order to make webpack configuration accessible. However, I am uncertain about what needs to be included in the webpack.config.js file to ensure that TailwindCSS ...

jQuery tipsy not triggering click event in Internet Explorer

Hey there! I've been using the jquery tipsy plugin for displaying colour names above colour swatch images. One thing I'm trying to do is trigger a checkbox to be checked/unchecked when a user clicks on the image. $(document).ready(function(){ ...

The outcome of a MySQL query involving JSON_OBJECT() is a string value

I have crafted a query that extracts posts from a table and includes information about each post's author: SELECT post.id, post.text, post.datetime, JSON_OBJECT( 'username', user.username, 'firstName', user.firstName, 'last ...

Ways to transform a PHP function into one that can be invoked using Ajax

In my current project, I’m facing an issue where I need to call multiple PHP functions that output HTML using Ajax. Instead of directly trying to call a PHP function with Javascript, I believe application routing can help the frontend hit the correct fun ...

Having issues showcasing the array of objects stored in $scope in AngularJs

I'm encountering an issue where I can't seem to display the values of my scope variables. Even though I'm new to Angular, I've successfully done this many times before. Here are the key parts of my index.html file. The div-ui element is ...

The JSON data retrieved from the API is showing as undefined for the property

Currently, I am working on a project that involves utilizing the Shopify API to fetch products and related data from a store in JSON format. While I was able to successfully retrieve the JSON object from the API, I encountered an issue when trying to acces ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

Executing a loop synchronously within an Angular application

I am grappling with Angular as I have an $http request retrieving multiple rows that need to be processed synchronously. The challenge arises when these records must be processed against a local SQLite database on an iOS device, which involves an asynchron ...

Tips for retrieving the first true value in an *ngIf statement within an *ngFor loop

I have an array of items that must be shown based on different roles. I am looking for the first item in the array that meets the ngIf condition. Below is my code snippet: This is how my Array initially looks: parentTabList = [ { nam ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

Transforming a namespaced function into an asynchronous operation by utilizing setTimeout

Looking for help with making a function that uses namespaces asynchronous. The function is currently being called on the click of a button. var ns = { somemfunc: function (data) { alert("hello"); } } Edit: ...

Incorporate a React web application seamlessly into a React Native WebView component

In my monorepo, I have a web app and a mobile app (built with React and React Native respectively). My goal is to embed the web app into the mobile app using React Native WebView. After reading the documentation, I learned that the source for the WebView ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Improving the functionality of the JavaScript key press function

I have a small javascript snippet on my website that allows me to navigate the site using the arrow keys on my keyboard. document.onkeydown = function(evt) { evt = evt || window.event; switch (evt.keyCode) { case 37: ...