Create a dynamic feature in Bootstrap4 where the navigation bar changes color as the user scrolls to different sections of the

Currently building my personal portfolio website with Bootstrap 4, I came up with a great idea: changing the navigation bar color based on different sections of the website. I attempted to achieve this using JQuery's offset and scrollTop functions, but encountered some issues. I am seeking guidance on how to properly implement this feature.

Here is the code snippet of the website:

<!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.2/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.2/js/bootstrap.min.js"></script>
</head>
<body>

<header id="change">
<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">About</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section3">Contact</a>
      </li>    
    </ul>
  </div>  
</nav>
</header>

<div id="section1" class="container-fluid bg-success" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 1</h1>
  <p>Try scrolling this section and observe the navigation bar color change!</p>
  <p>Try scrolling this section and observe the navigation bar color change!</p>
</div>
<div id="section2" class="container-fluid bg-warning" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 2</h1>
  <p>Try scrolling this section and observe the navigation bar color change!</p>
  <p>Try scrolling this section and observe the navigation bar color change!</p>
</div>
<div id="section3" class="container-fluid bg-secondary" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 3</h1>
  <p>Try scrolling this section and observe the navigation bar color change!</p>
  <p>Try scrolling this section and observe the navigation bar color change!</p>
</div>


<script>

var top1 = $('#section1').offset().top;
var top2 = $('#section2').offset().top;
var top3 = $('#section3').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 && scrollPos < top2) {
    $('#change').css('background-color', '#f00');
  } else if (scrollPos >= top2 && scrollPos < top3) {
    $('#change').css('background-color', '#0f0');
  } else if (scrollPos >= top3) {
    $('#change').css('background-color', '#00f');
  }
});

</script>

</body>
</html>

Grateful in advance for any assistance provided.

Answer №1

The Background-color in the navbar is determined by the "bg-dark" class, so one approach could involve adding or removing classes directly on the navbar to change the background color. To illustrate, I have defined a few custom background-color classes and applied them to the navbar using an id. While there may be more efficient solutions available, this example serves to demonstrate the concept.

.bg-purple {
  background-color: purple;
}

.bg-cyan {
  background-color: cyan;
}

.bg-orange {
  background-color: orange;
}
<!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.2/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.2/js/bootstrap.min.js"></script>
</head>
<body>

<header id="change">
<nav id="navbar-change" class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">about</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section3">Contact</a>
      </li>    
    </ul>
  </div>  
</nav>
</header>

<div id="section1" class="container-fluid bg-success" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 1</h1>
  <p>Try scrolling this section and observe the navigation bar's background color change!</p>
  <p>Try scrolling this section and observe the navigation bar's background color change!</p>
</div>
<div id="section2" class="container-fluid bg-warning" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 2</h1>
  <p>Try scrolling this section and observe the navigation bar's background color change!</p>
  <p>Try scrolling this section and observe the navigation bar's background color change!</p>
</div>
<div id="section3" class="container-fluid bg-secondary" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 3</h1>
  <p>Try scrolling this section and observe the navigation bar's background color change!</p>
  <p>Try scrolling this section and observe the navigation bar's background color change!</p>
</div>

<script>

var top1 = $('#section1').offset().top;
var top2 = $('#section2').offset().top;
var top3 = $('#section3').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 && scrollPos < top2) {
    $('#navbar-change').removeClass('bg-dark');
    $('#navbar-change').removeClass('bg-cyan');
    $('#navbar-change').removeClass('bg-orange');
    $('#navbar-change').addClass('bg-purple');
  } else if (scrollPos >= top2 && scrollPos < top3) {
     $('#navbar-change').removeClass('bg-dark');
     $('#navbar-change').removeClass('bg-purple');
     $('#navbar-change').removeClass('bg-orange');
     $('#navbar-change').addClass('bg-cyan');
  } else if (scrollPos >= top3) {
     $('#navbar-change').removeClass('bg-dark');
     $('#navbar-change').removeClass('bg-purple');
     $('#navbar-change').removeClass('bg-cyan');
     $('#navbar-change').addClass('bg-orange');
  }
});

</script>

</body>
</html>

Answer №2

To ensure the background color is applied to the .navbar element, you need to include the background color directly in the CSS for .navbar as the bg-dark class has a !important declaration. To override this, utilize the cssText property with your desired background color value.

var top1 = $('#section1').offset().top;
var top2 = $('#section2').offset().top;
var top3 = $('#section3').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 && scrollPos < top2) {
    $('#change .navbar').css("cssText", 'background:#f00!important');
  } else if (scrollPos >= top2 && scrollPos < top3) {
    $('#change .navbar').css("cssText", 'background:#0f0!important');
  } else if (scrollPos >= top3) {
    $('#change .navbar').css("cssText", 'background:#00f!important');
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/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.2/js/bootstrap.min.js"></script>

<header id="change">
<nav class="navbar navbar-expand-md bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#section1">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section2">about</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section3">Contact</a>
      </li>    
    </ul>
  </div>  
</nav>
</header>

<div id="section1" class="container-fluid bg-success" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 1</h1>
  <p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
  <p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
<div id="section2" class="container-fluid bg-warning" style="padding-top:70px;height: 100vh;width:100%;">
  <h1>Section 2</h1>
  <p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
  <p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
<div id="section3" class="container-fluid bg-secondary" style="padding-top:70px;heigth;height: 100vh;width:100%;">
  <h1>Section 3</h1>
  <p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
  <p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>

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

EJS causing issues with Bootstrap tooltip functionality

I have implemented tooltips by adding the necessary script to my ejs file and including CDN links for Bootstrap, Popper, and jQuery. However, I am still facing issues with invoking the tooltips. Is there something crucial that I might be overlooking or a ...

Highlight columns and rows when hovered over in a striped table using CSS styling

I have successfully implemented a CSS-only method for highlighting table columns on hover from a tutorial I found at https://css-tricks.com/simple-css-row-column-highlighting/ However, I am encountering an issue with applying the highlight to striped tabl ...

Analysis of printing functionality across Chrome, Safari, and Firefox browsers

When utilizing the print function of various browsers to save web content in a PDF file, I have observed that each browser behaves differently. This becomes an issue when the content spans multiple pages. For instance, Chrome prints correctly while Safari ...

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

How to Retrieve the Value of <input type=date> Using TypeScript

I am currently developing a survey website and need assistance with retrieving user input for two specific dates: the start date and end date. I aim to make the survey accessible only between these dates, disabling the "take survey" button after the end da ...

What is the best way to programmatically route or navigate to a specific route within a Next.js class component?

tag: In the process of creating my app with next.js, I primarily use functional components. The sole exception is a class component that I utilize to manage forms. Upon form submission, my goal is to redirect back to the home page. However, when I attemp ...

Replacing variables in a function: A step-by-step guide

I have frequently used the replace function to eliminate classes in JavaScript. Currently, I am working on creating a JavaScript function that allows me to remove a specific class from an element by passing in the element and the class name. changeAddress ...

Updating a component from a different source

As a newcomer to React, I'm curious about the ability to update one component's content based on events from another component. I have two React components set up. The first component loads data when the page initializes, while the second compon ...

The AJAX functionality is not functioning properly on the remote server, although it is working fine on localhost within the MVC.NET framework

While everything seems to work fine on localhost, the deployment version is encountering issues. I am utilizing jQuery for deletion from the controller: I have tried using type: delete, as well as get and POST methods but still face difficulties. $("#btn ...

Creating a div larger in size than the wrapper

Would it be feasible to have a container with a width of 1000px;, while simultaneously having a DIV inside the container that has a width of 100%? Is that achievable in any way? Here is a snippet of my code: <div class="block1"> <img src="i ...

What could be causing my browser to not respond to the JavaScript function for clicking?

I have been struggling to get the images on my browser to change when I click on them. Despite my efforts, I haven't found a solution yet... I've experimented with changing the variables to ".jpg" and also tried removing them altogether. var ...

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached https:// ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Is there a way to incorporate an 'input' type within an Icon Button component from Material UI in a React project?

Kindly review my code below. I have revamped it for clarity so you won't need to stress about important details! const test = () => { return ( <label > <input type='file' multiple style={{ display: &ap ...

Sending JSON data to Python CGI script

I've successfully set up Apache2 and got Python running without any issues. However, I'm facing a problem with two pages - one is a Python Page and the other is an HTML page with JQuery. Could someone guide me on how to correctly make my ajax p ...

What is the reason behind jQuery onePageNav adding the 'current' class to each 'li' element?

When the jQuery function is applied to the .navbar.navbar-fixed-top .navbar-nav, it triggers an event that changes the current class to 'active', disables hash change, sets scroll speed to 400 and applies a filter excluding elements with the &apo ...

Receiving the error message "Encountered SyntaxError: Unexpected token )" when using a custom directive

Encountering an issue with the customer directive of auto-complete, as I am receiving the error Uncaught SyntaxError: Unexpected token ). This error is displayed in the console of the chrome browser as VM80623:1 Uncaught SyntaxError: Unexpected token ). Cl ...

Using a variable to contain a loop in Jquery

Seeking assistance with a jQuery function that retrieves values from a PHP form to create a variable for an ajax call. Is it possible to include a loop within a variable? Below is a snippet of my code to provide better context: ... var teacher_ids = $( & ...

Getting the number of ticks from an rxjs Observable is a simple process that involves extracting

Is there a way to track how many times this observable has run? this.clock = Observable.interval(1000).map(function(value){ if(value == 0){ return value * 100 / 60; } return value * 100 / 60; }).take(61); I would like to kno ...