Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. However, the navbar icon remains white, causing it to disappear when scrolling. I know I can resolve this by switching the navbar class from 'navbar-dark' to 'navbar-light'. But I am unsure of how to accomplish this using javascript.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <style>
      .navbar{
        background-color: black !important;
      }
      div.navbar.scrolled {
        background-color: white !important;
      }
       div.navbar.scrolled .navbar-brand{
        color: black !important;
      }
    </style>
  </head>
  <body>
    <header>
      <div class="container-fluid">
        <div class="navbar navbar-dark navbar-expand-md fixed-top">
          <a class="navbar-brand" href="#">Brand</a>
          <button
            class="navbar-toggler"
            data-toggle="collapse"
            data-target="#uniqueIdentifier"
          >
            <span class="navbar-toggler-icon"></span>
          </button>
          <div id="uniqueIdentifier" class="collapse navbar-collapse">
            <ul class="navbar-nav ml-auto">
              <li class="nav-item">
                <a class="nav-link" href="#">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Skills</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="content" style="height:200vh;"></div>
    </header>
    <script>
      $(window).scroll(function() {
        $("div.navbar").toggleClass('navbar-dark');
        $("div.navbar").toggleClass('navbar-light');


        $("div.navbar").toggleClass("scrolled", $(this).scrollTop() > 200);
      });
    </script>
  </body>
</html>

Answer №1

You have the ability to switch between dark and light modes depending on the scroll position.

$("div.navbar").toggleClass('navbar-light', $(this).scrollTop() > 200).toggleClass('navbar-dark', $(this).scrollTop() <= 200);

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <style>
      .navbar{
        background-color: black !important;
      }
      div.navbar.scrolled {
        background-color: white !important;
      }
       div.navbar.scrolled .navbar-brand{
        color: black !important;
      }
    </style>
  </head>
  <body>
    <header>
      <div class="container-fluid">
        <div class="navbar navbar-dark navbar-expand-md fixed-top">
          <a class="navbar-brand" href="#">Brand</a>
          <button
            class="navbar-toggler"
            data-toggle="collapse"
            data-target="#uniqueIdentifier"
          >
            <span class="navbar-toggler-icon"></span>
          </button>
          <div id="uniqueIdentifier" class="collapse navbar-collapse">
            <ul class="navbar-nav ml-auto">
              <li class="nav-item">
                <a class="nav-link" href="#">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Skills</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="content" style="height:200vh;"></div>
    </header>
    <script>
      $(window).scroll(function() {
        $("div.navbar").toggleClass("scrolled", $(this).scrollTop() > 200);
        $("div.navbar").toggleClass('navbar-light', $(this).scrollTop() > 200).toggleClass('navbar-dark', $(this).scrollTop() <= 200);
      });
    </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

Is it considered a bad practice to apply overflow: auto to all elements with the exception of html?

My approach to beginning a new design always involves overriding the default padding and margin set by the browser on all elements: * { margin: 0; padding: 0; } After coming across j08691's response regarding a margin collapse issue, I discovered th ...

Using jQuery to obtain the object context while inside a callback function

Suppose I have the following object defined: var myObj = function(){ this.hello = "Hello,"; } myObj.prototype.sayHello = function(){ var persons = {"Jim", "Joe", "Doe","John"}; $.each(persons, function(i, person){ console.log(this.h ...

Header that sticks to the top of a container as you scroll through it

Many questions arise regarding sticky elements in the DOM and the various libraries available to handle them, such as jquery.pin, sticky-kit, and more. However, the issue with most of these libraries is that they only function when the entire body is scro ...

Problem with traversing from parent to children elements using jQuery selectors

<form data-v-c4600f50="" novalidate="novalidate" class="v-form"> <div data-v-c4600f50="" class="pr-2" question="Top Secret4"> <div data-v-c4600f50="" f ...

exploring the network of connections

This is what the HTML structure of the webpage looks like: <body> <form> <input type='file'/> </form> <div id='list'> <div>value here<input id='delete' type='button'/>< ...

I am currently having trouble with req.query not functioning correctly within Next.js for reading query parameters

I am facing an issue while working with a REST API in Next.js 13. I have created the API, which can be accessed at http://localhost:3000/api/portfolio. However, when I try to filter the data using query parameters like http://localhost:3000/api/portfolio?s ...

Tips for creating a div that covers the entire screen and prevents it from resizing

I am facing an issue with a container having the className "container". When I set the height to 100vh like this: .container{ height:100vh } Whenever I resize my screen, such as with dev-tools, the div also shrinks. How can I prevent this? Is it possi ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Delete specific rows by clicking a button in AngularJS

I have a table with checkboxes for each row and I am trying remove the selected rows when a button is clicked. The selected row indexes are stored in an array using ng-change, but I cannot figure out how to delete them all at once with a single button clic ...

Converting from CAPS lock to using the capitalize property in CSS

Is there a way to transform a sentence that is all in CAPs lock without changing it? This sentence is part of a paragraph, and I am looking for a CSS solution (maybe with a little Jquery) that works reliably across most devices! I have come across similar ...

A script page in Wordpress generates a numerical value in the URL

I created a script named search.php which utilizes various search engines APIs to display search results. From this file, I have developed a Page template and incorporated the simplePagination plugin The issue arises when I click on a page within the pag ...

Issue with dynamic form JavaScript functionality after removing curly braces { } from a select tag in Rails

In my Rails form, there is a gender field defined as follows: <%= f.select :gender, ["Male","Female"],{class: "gender"} %> I also tried adding an onclick event like this: <%= f.select :gender, ["Male","Female"],{class: "gender"},onclick: "categ ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

Issue with AngularJS binding not updating when the initial value is null and then changed

I am encountering an issue with my binding not updating, and I have a hypothesis on why it's occurring, but I'm unsure about how to resolve it. Within my controller, there is a company object that includes a property called user, which may or ma ...

Sequencing numerous promises (managing callbacks)

I am encountering some challenges with promises when it comes to chaining multiple ones. I'm having difficulty distinguishing how to effectively utilize promises and their differences with callbacks. I've noticed that sometimes callbacks are trig ...

Executing a custom object function in AngularJS by using the ng-click directive

As I navigate my way through AngularJS, I find myself grappling with the concept of calling a custom method of an object and wonder if there's a simpler approach: https://jsfiddle.net/f4ew9csr/3/ <div ng-app="myApp" ng-controller="myCtrl as myCtr ...

The array is arranged properly, yet React is failing to render it in the correct order

Here's the code snippet I am working with: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => !defectsArray.includes(qc3.Defect) &am ...

Flashing white screen when transitioning between pages on phonegap iOS system

I'm currently using phonegap for my iOS application project. Interestingly, I've noticed a slight white flicker/flash when navigating between pages in the app. To address this issue, I have refrained from using jquery mobile and instead relied ...

Tips for including a header with Apollo Client in a React Native app

In my React Native application, here's how I set up the Apollo client with an upload link: My goal is to include a header with a token value that will be sent with every request. However, I've had trouble finding an example specifically for Reac ...

What is the best way to adjust the size of a button using CSS within a ReactJS

I am facing an issue where I need to create a button with a specific width, but the template I'm using already has predefined styles for buttons. When I try to customize the button's style, nothing seems to change. Below is the code snippet: Her ...