Having trouble with the background color not changing on scroll in Bootstrap 5 navbar?

I have gone through other posts, and I didn't encounter this issue while working on a regular html/css/js project. However, I need bootstrap for this particular project, and I believe it might be somehow interfering with my script, but I'm unsure how.

When scrolling, I want the color to transition from transparent to x. I also aim to update the styling of all navbar elements, possibly reducing the size on scroll. However, I attempted to change the color initially before delving deeper, and even that is not functioning as expected.

Is there anyone who could guide me through this?

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
    />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="./assets/styles/bootstrap.css" />
    <link rel="stylesheet" href="./assets/styles/index.css" />
    <link
      rel="icon"
      type="image/ico"
      href="./assets/images/favicon/favicon.ico"
    />
    <link
      rel="icon"
      type="image/png"
      href="./assets/images/favicon/favicon.png"
    />
    <title>test</title>
  </head>
  <body>
    <!--Navbar Start-->
    <nav class="navbar fixed-top navbar-expand-lg" id="nav">
      <a class="lang-btn" href="#"><span>LANG</span></a>

      <div class="container-fluid">
        <a class="navbar-brand" href="#"
          ><img
            src="./assets/images/logo_light.svg"
            alt="test logo"
            class="test-logo-light"
        />
        <!-- <img
            src="./assets/images/Logo_Dark.svg"
            alt="test logo"
            class="test-logo-dark"
        /> -->
      </a>
        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarNav"
          aria-controls="navbarNav"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse ms-auto" id="navbarNav">
          <ul class="navbar-nav ms-auto">
            <li class="nav-item">
              <a class="nav-link active" aria-current="page" href="#">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">About Us</a>
            </li>
          </ul>
          <div class="navbar-nav ms-auto">
            <div class="settings">
              <div class="nav-contact">
                <span>Get in Touch</span>
                <a href="tel:+00000" class="digit">00000</a>
              </div>
              <div class="nav-account">
                <a href="#">
                  <img
                    src="./assets/images/MyAccount_icon_white.svg"
                    alt="my-account-icon"
                  />
                >
                <a href="#">
                  <img
                    src="./assets/images/Register_icon_white.svg"
                    alt="my-account-icon"
                  />
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </nav>
    <!--Navbar End-->

   
    <!-- Bootstrap Bundle with Popper -->
    <script
      src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4868b8b909790968594a4d1cad4cad6">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
      crossorigin="anonymous"
    ></script>
    <script src="./scripts/bootstrap.js"></script>
    <script src="./scripts/script.js"></script>
  </body>
</html>

CSS

.navbar {
  flex-direction: column;
  margin: 0;
  padding: 0;
  top: 0;
  text-transform: uppercase;
  background-color: transparent !important;
}
.navbar.scrolled{
  flex-direction: column;
  margin: 0;
  padding: 0;
  top: 0;
  text-transform: uppercase;
  background-color: #38456b !important;
}

.navbar .container-fluid {
  padding: 0 4rem;
}

.navbar .container-fluid .collapse ul li {
  margin-top: 1vh;
}

.navbar-nav .nav-item .nav-link {
  display: inline-block;
  text-transform: uppercase;
  font-family: "Georama";
  font-size: 0.9rem;
  line-height: 1.5rem;
  font-weight: light;
  color: var(--white);
  margin: 0.3rem 0.3rem;
  transform: 1s ease-in-out;
}

JS

$(window).scroll(function(){
    $('nav').toggleClass('scrolled', $(this).scrollTop()> 50)
})

Answer №1

Follow this sample:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2d20203b3c3b3d2e3f0f7a617f617d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57353838232423253627176279677965">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <title>test</title>
    </head>
    <style>
        nav {
            text-align: center;
            position: fixed !important;
            top: 0;
            width: 100%;
            z-index: 100;
            opacity: 40%; /* modify the degree of transparency here */
            }
    </style>
    <body>
        <nav class="navbar navbar-dark" style="background-color: rgb(100, 142, 142);" id="myNAV">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">Navbar</a>
            </div>
        </nav>
        <div class="py-4"></div>
        <div class="py-4"></div>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
        <p>Update the content here.</p>
    </body>
    <script>
        document.addEventListener("scroll", myFunction);
        function myFunction() {
            if (document.documentElement.scrollTop == 0){
                // modify the degree of transparency here
                document.getElementById("myNAV").style.opacity = "40%";
            }else{
                document.getElementById("myNAV").style.opacity = "100%";
            }
        }
    </script>
    </html>

Answer №2

Oh dear, what a silly mistake! It slipped my mind, but the missing piece was just the jQuery script that I forgot to include!

Don't forget to place it in the head section of your code.

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

AngularJs: Activate the Submit Button only when a file upload path has been chosen

Hey, I'm currently learning AngularJS and I'm trying to figure out how to disable the upload button until a file is selected. I've tried the code below, and while the button gets disabled, it doesn't become enabled after selecting a fil ...

Identifying a shift in data model within a component

It seems like there's a piece I might be overlooking, but here's my current situation - I have data that is being linked to the ngModel input of a component, like so: Typescript: SomeData = { SomeValue: 'bar' } Snippet from the vie ...

Jquery code fails to execute unless a breakpoint is set

I'm encountering a strange issue with the jquery star rating plugin. It seems that only when there's a breakpoint in my JS code will the radio buttons transform into stars; otherwise, they remain unchanged. Let me break down the code step by step ...

What is the best method for inserting dynamic HTML content (DIV) with JavaScript?

Can someone assist me in dynamically adding HTML content when data is returned from the server-side? I am currently using ajax/jQuery to handle server-side processing requirements. The success code section of my ajax function allows me to write HTML elemen ...

Creating a smaller (child) div within a larger div (parent) using Bootstrap 5

I am looking to use bootstrap5 to create a smaller div in the bottom right corner of a parent div. Both divs need to be responsive as they will contain video content. According to the Bootstrap Utilities Docs, this can be achieved with the following code: ...

How can I utilize CSS shapes to create clickable images?

I'm facing a challenge in making an input field and button functional even when they are positioned behind a uniquely shaped PNG image. https://i.stack.imgur.com/eOg0N.jpg Initially, I believed that by applying a shape to the image, it would automat ...

Tips for inserting a blank space into a text box

It feels like such a simple issue, but my function is incorrectly returning "1" instead of just an empty space "" in my textbox. <td><input type="button" value="Space" name="Space" onClick='document.firstChild.search.value = document.firstCh ...

Leveraging external JavaScript libraries in SAPUI5

I'm currently facing an issue while trying to include an external .js file in my SAPUI5 Controller. jQuery.sap.includeScript("externalLibrary.min.js", function() { // initializing objects from the library }); Despite setting up ...

Calculating the angle formed by three vectors in three-dimensional space

According to the solution(s) provided in this post Angle between 3 points in 3d space, there is a JavaScipt function that calculates the angles between three vectors in 3D space. The function calculates the angles as if each vector is a vertex on a surface ...

JavaScript's multiple inheritance concept

In the realm of JavaScript, there exists a class that seeks to 'inherit' various objects and their methods. var A = function (a,c){}; var N = { properties1: function(){}; }; var M1 = { properties2: function(){}; }; var M2 = { ...

Python Selenium Webdriver: Dealing with the NoSuchElementException

I've encountered a strange situation while using Selenium Webdriver for Python on the Chrome browser. My goal is to extract information from Pipedrive, where I can successfully log in and search for a specific lead on the webpage. However, when I atte ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Using JavaScript to pass the href attribute value

On my HTML page, there are multiple links that reload the page when clicked. I want to capture the href value of each link the user clicks and store it in a variable called xhash: Here is the HTML: <a href='#taba' id='passid'>Li ...

conceal the offspring from the guardians, not the offspring

Could you please assist me with this situation... <li id="4331">Region <ul> <li id="4332">Asia</li> <li id="6621">Europe</li> </ul> </li> I have a query when I click on the Reg ...

Unable to disable webpack HMR

I have set up my project using express version 4.14.0, webpack version 1.14.0 with babel and its presets. I obtained this sample webpack configuration from a reliable source: var path = require('path'); module.exports = { entry: './main. ...

Does the AngularJS inject function operate synchronously?

Does the AngularJS inject method work synchronously? Here is an example: inject(function(_$compile_, _$rootScope_) { $compile = _$compile_; rootScope = _$rootScope_.$new(); }); ...

Increase value by 1 with the push of a button within two specified ranges using JavaScript

I am looking to create buttons that will increase the value of both the first and second range by 1 when pressed, as well as decrease the value of both ranges by 1 when pressed. Here is my code: function run(){ var one = document.getElementById("rang ...

After running the `npm run build` command in a Svelte (not Svelte Kit) application, the index.html file displays as

When I run the npm run dev server, it displays the default counter app that is built. However, if I build a plain HTML, CSS, and JavaScript project using npm run build in the dist folder, then open the index.html file, it shows a blank page even though the ...

Conditional statement that includes Node.js scheduling function

I am currently working on a Node.js project and I need to execute a specific portion of conditional code after waiting for five minutes since the last piece of code executed. This action should only happen once, not on a daily basis or any other frequency. ...

Web GUI for insert, update, and delete functionalities

After repeatedly creating Add/Edit/Delete/List GUI's, I have grown weary and frustrated with the process. Surely, there must be a free package available that can simplify this tedious task. I envision something like the following code snippet: { ...