What is the best way to modify navbar-default to navbar-inverse when scrolling?

On the header of my webpage, the primary navigation class is called:

navbar navbar-default navbar-fixed-top bg

I am attempting to create a smoother scroll animation by changing the class when scrolling as follows:

navbar navbar-inverse navbar-fixed-top bg

How can I achieve this using Javascript? I haven't been able to find any resources online...the one solution I did come across only allowed for removing one class at a time which doesn't work in my case where multiple classes are used simultaneously...

Answer №1

Let's illustrate this with a practical example.

To make your navigation bar change background color when you scroll down past a specific point, you can utilize $(window).scroll() and addClass(). Keep in mind that using addClass and removeClass allows you to add or remove individual class names from elements containing multiple classes.

It is important to note that you may need to employ !important to enforce the color change, as bootstrap styles can be quite persistent.

var visible = true;
var win = $(window);
var nav = $('nav');

win.scroll(function(){
    var position = win.scrollTop();
  
    if (visible && position > 100){
        visible = false;
        nav.addClass('bg');
    } else if (!visible && position < 100){
        visible = true;
        nav.removeClass('bg');
    }
});
body,
html {
  height: 2000px;
}
.bg{
    background: green !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span> 
      </button>
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a>
        </li>
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1
        <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Page 1-1</a>
            </li>
            <li><a href="#">Page 1-2</a>
            </li>
            <li><a href="#">Page 1-3</a>
            </li>
          </ul>
        </li>
        <li><a href="#">Page 2</a>
        </li>
        <li><a href="#">Page 3</a>
        </li>
      </ul>
    </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

Using the useState hook in a Node.js backend and React frontend: a comprehensive guide

How can I use useState in my HTML file that already uses node.js? const {useState} = React Below is the code snippet: const {useState} = React; function App(){ const {text, setText} = useState("Hello world") console.log(text); function handleClick(){ se ...

Access the value of a submitted form using jQuery, when there are multiple forms with identical class names

I've looked for a solution here but couldn't find one that meets my needs. I have multiple forms with the class name .sbt-form: <form class='sbt-form'> <input name='kord' val=1/> </form> <form class= ...

The requested resource at http://js:port/socket.io/1/ could not be located (Error 404

Having trouble connecting with Socket.io. This is the server-side code: function chatserver(){ var express = require('express'), app = express(), server = require('http').createServer(app).listen(app.get('port'),function ...

Removing files from the S3 bucket and database simultaneously. Execute each function sequentially

Struggling with an API call that should delete an image from both an S3 bucket and a MySQL database. However, encountering an issue where the S3 image cannot be found because it is being deleted from the database first. // Router code: //req.body is an ar ...

Integrate a new Webview Window into an existing iOS App to display locally stored HTML content

Integrate a WebView Window into an existing iOS application to display locally stored HTML content. I have already completed the feed RSS feature in my app, but now there is a requirement for a section that can be easily updated... ...

Angularjs collapsible toggle

I am having trouble launching a simple example of collapse. When I click on the "Toggle collapse" button, nothing happens. There are no errors in the console, but there is one warning in Visual Studio. What could be causing this issue and how can I fix it? ...

What is the best way to alternate $httpBackend when[method] declarations in unit tests to handle multiple requests?

When conducting my testing, I set up the model data and mock the response: beforeEach(function(){ var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/); $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000}); }) ...

What is the best way to implement CSS text-overflow after a specific amount of text, such as two lines?

Although this question is similar to another one (Wrap a text within only two lines inside div), I couldn't find a satisfactory answer in that thread. Here's my dilemma: I have a DIV with fixed width and height, but it needs to accommodate text ...

Tips for loading a webpage with optimal speed and efficiency

I am inspired by the sleek design of Apple's website and want to replicate some of its features in my project (best viewed on FF, Chrome, Safari): Initially, the page appears empty except for the header - but the final height of the page is already ...

Refresh all color pickers with Bootstrap 4 Colorpicker - enforce the update of every color selector

Currently, I am utilizing the Bootstrap 4 color picker library which can be found at this link: In my code, I have defined color pickers that look like this: <div class="input-group cpicker"> <input type="text" class="form-control input-lg" ...

Tips for incorporating a pause or delay into if-else statements

Trying to optimize my semi-automated JavaScript code so it runs at a slower pace. Currently, it fetches detailed data from 100 listings one by one at a speed of around 15 times per second. While this works well in some aspects, it makes tracking which elem ...

The console is failing to display the value associated with the key

In this snippet of JSON code, the key "pants" is nested under the "children" key for MALE when gender is selected as male. However, if the selected gender is female, then "pants" becomes a children key of FEMALE. var data = { "gender": "male", "myFi ...

Creating a Dual Linear Gradient Background with Tailwind: Step-by-Step Guide

Can you use two linear backgrounds on a single element in Tailwind CSS? I found this CSS code that seems to achieve it: background-image: linear-gradient(to right, #f8fafb 50%, #161616 50%), linear-gradient(to right, #161616 50%, #f8fafb 50%); I att ...

A secret form input unexpectedly triggers the expansion of a table cell in IE7 (see image)

I've encountered a strange issue where a form inside a table cell with hidden inputs causes the cell to expand in IE7 once there are more than one hidden input present. Here is a screenshot showing the problem: Here is the HTML code: <table bord ...

Securing applications and code

I am faced with a scenario where I have five unique applications, each programmed in a different language, deployed on a single web server. These applications are designed to carry out specific tasks and generate log files for every action taken. How can ...

Creating HTML dynamically in ASP.NET: What's the best approach?

Throughout the past year, I've dabbled in ASP.NET on and off. However, I am currently facing a new challenge while working on a simple website that mainly consists of HTML and Javascript. On one specific page, I need to retrieve an XML file from the s ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

"Enhance your form design with a Bootstrap Horizontal Form label paired with a subtle

How can I add a caption right below the Order label in this Bootstrap Horizontal form? The caption should be <small class="text-muted">Must be at least 200</small>. Where should it be placed? Please note that I need to place this muted caption ...

Guide to showcasing an Expo camera image in a React Native app

I have been working on an app that involves camera functionality. I have successfully taken a picture and converted it into base64 format. However, I am facing an issue when trying to display the image. Can someone please assist me in achieving this goal? ...

Every time I try to deploy my app on Heroku, it keeps crashing with a strange error popping up on the home screen

Here are the logs for my application: 2018-07-19T01:40:27.548845+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16) 2018-07-19T01:40:27.548847+00:00 app[web.1]: at Module._compile (module.js:652:30) 2018-07-19T01:40:27 ...