Transform the appearance of the navigation bar background upon scrolling in Bootstrap

I am trying to change the background color of my navigation bar from transparent to black when scrolling. I want it to function like this template: . Previous attempts using solutions from How to Change Navigation Bar Background with Scroll? and Changing nav-bar color after scrolling? have not worked for me.

This is an example of my HTML code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>Cuppela</title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <script src="js/bootstrap.min.js" type="text/javascript"></script>
    <script src="js/popper.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="css/test.css" type="text/css">
</head>
<body>
<div id="nav-menu">
    <nav id="main-nav" class="navbar navbar-expand-md fixed-top navbar-dark bg-transparent">
        <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="nav navbar-nav mx-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Shop</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
            </ul>
        </div>
    </nav>
</div>
<div class="container-fluid" id="top-main"> 

    <div id="top_text">
        <h1>Cuppela Made With Sugar</h1>
        <p style="font-size: x-large;">Delicious Homemade Cakes</p>
    </div>
    
</div>

<div id="best-sellers "class="container">
    <h2>Best Sellers</h2>
    <hr>
    <div id="best-seller-cakes" class="row">
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="images/chocolate_cake.jpg">
            <h4>Good<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</p>
        </div>
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="images/red_velvet_cake.jpeg">
            <h4>Awesome<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</p>
        </div>
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="images/strawberry_cake.jpg">
            <h4>Great<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</p>
        </div>
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="images/cake_seven.jpg">
            <h4>Delicious<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</p>
        </div>
    </div>
</div>

<footer>
    <div class="container-fluid" id="footer-content">
    <h3>Test</h3>
    </div>
</footer>

<script type="text/javascript">
$(document).ready(function(){
    $(window).on("scroll",function(){

        if($(document).scrollTop() > 50)
        {
            $("#nav-menu").css({background:"black"});
        }
        else
        {
            $("#nav-menu").css({background:"transparent"});
        }
    })
});
</script>

</body>
</html>

This is a snippet from my CSS file:

body{
    margin: 0px;
}

li a:hover {
    background-color: #ff9900;
    border-radius: 10px;
}

li a{
    color: white !important;
}

.nav-link{
    padding: 0 0 .2rem
}

#top-main{
    background-image: url(../images/cake_six_two.jpg);
    height: 100vh;
}

#nav-menu{
    font-size: medium;
    position: relative;
}

#top_text{
    color: white;
    text-align: center;
    position: relative;
    top: 50%;
    left: 50%;
    /* bring your own prefixes */
    transform: translate(-50%, -50%);
}

h1{
    font-size: 500%;
    text-align: center;
}


h2{
    text-align: center;
}

#best-sellers{
    text-align: center;
}

#best-seller-cakes{
    text-align: center;
}

h4{
    font-size: x-large;
    font-weight: bold;
    font-family: Georgia, 'Times New Roman', Times, serif;
}

#footer-content{
    text-align: center;
}

Answer №1

Toggle class in jQuery for #main-nav instead of #nav-menu.

Check out the code snippet below.

$(document).ready(function () {
    $(window).on("scroll", function () {
        if ($(document).scrollTop() > 50) {
            $("#main-nav").addClass('bg-dark').removeClass('bg-transparent');
        }
        else {
            $("#main-nav").addClass('bg-transparent').removeClass('bg-dark');
        }
    })
});
li a:hover {
    background-color: #ff9900;
    border-radius: 10px;
}
li a{
    color: white !important;
}
.nav-link{
    padding: 0 0 .2rem
}
#top-main{
    background-image: url(https://i.sstatic.net/Z12tw.png);
    height: 100vh;
}
#nav-menu{
    font-size: medium;
    position: relative;
}
#top_text{
    color: white;
    text-align: center;
    position: relative;
    top: 50%;
    left: 50%;
    /* bring your own prefixes */
    transform: translate(-50%, -50%);
}
h1{
    font-size: 500%;
    text-align: center;
}
h4{
    font-size: x-large;
    font-weight: bold;
    font-family: Georgia, 'Times New Roman', Times, serif;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab8b5b5aea9aea8bbaa9aeff4ebf4ea">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a7975687f5a2834233429">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89ebe6e6fdfafdfbe8f9c9bca7b8a7b9">[email protected]</a>/dist/js/bootstrap.min.js" ></script>


<div id="nav-menu">
    <nav id="main-nav" class="navbar navbar-expand-md fixed-top navbar-dark bg-transparent">
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
            <ul class="nav navbar-nav mx-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Shop</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
            </ul>
        </div>
    </nav>
</div>

<div class="container-fluid" id="top-main">
    <div id="top_text">
        <h1>Cuppela Made With Sugar</h1>
        <p style="font-size: x-large;">Delicious Homemade Cakes</pp>
    </div>
</div>

<div id="best-sellers" class="container text-center">
    <h2>Best Sellers</h2>
    <hr>
    <div id="best-seller-cakes" class="row text-center">
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="https://i.sstatic.net/Z12tw.png" class="w-100">
            <h4>Good<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</pp>
        </div>
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="https://i.sstatic.net/Z12tw.png" class="w-100">
            <h4>Awesome<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</pp>
        </div>
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="https://i.sstatic.net/Z12tw.png" class="w-100">
            <h4>Great<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</pp>
        </div>
        <div class="col-xs-12 col-sm-6 col-lg-3">
            <img src="https://i.sstatic.net/Z12tw.png" class="w-100">
            <h4>Delicious<br>Cakes</h4>
            <p>Delicious Cake with Awesome Goodness</pp>
        </div>
    </div>
</div>

<footer>
    <div class="container-fluid text-center" id="footer-content">
        <h3>Test</h3>
    </div>
</footer>

Answer №2

Okay, so you're utilizing Bootstrap. The first step is to eliminate the bg-transparent class since it has a background color defined with !important:

https://i.sstatic.net/mFoBz.png

Below is a tested and functional solution for your issue:

(function($){
    $(window).on("scroll",function(){
        var $navbar = $('#main-nav');
        if($(document).scrollTop() > ($navbar.height()+10))
        {
            $navbar
                .removeClass('bg-transparent')
                .addClass('bg-dark');
        }
        else
        {
            $navbar
                .addClass('bg-transparent')
                .removeClass('bg-dark');
        }
    });
}(jQuery || window.jQuery));

How does this code work?

Essentially, as the user scrolls, the script checks how far down the document is from the top of the screen. It calculates the header height and adds 10px to account for some offset.

If the position of the document surpasses the height of the header (indicating scrolling downward), the transparent background is removed and replaced with a black background. On scrolling back up, the black background is removed, restoring the transparency.

The script automatically toggles between classes in the header element.

Answer №3

Give this method a try

I made a change from Target #nav-menu to #main-nav

$(document).ready(function(){
    $(window).on("scroll",function(){

        if($(document).scrollTop() > 50)
        {
            $("#main-nav").css('background', 'black !important;');
        }
        else
        {
            $("#main-nav").css('background','transparent !important;'});
        }
    })
});

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

Unable to invoke any fineUploader functions within a callback function

My autoUpload is currently set to false because I prefer uploading the images manually to my backend. To achieve this, I need the file object first. In the onSubmitted event callbacks, I am attempting to pass the image's ID to the getFile method to re ...

Require assistance with try-catch statements

I am troubleshooting an issue with a try-catch block in my Protractor test. Take a look at the code snippet below: try { element(by.id('usernameas')).sendKeys(data); } catch(err) { console.log('error occurred'); } To test the ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Disappear scrollbar when overlay is activated

How can I hide the scroll bar when an overlay is displayed on my page? .overlay{ display: none; opacity:0.8; background-color:#ccc; position:fixed; width:100%; height:10 ...

Maintaining the dropdown in the open position after choosing a dropdown item

The dropdown menu in use is from a bootstrap framework. See the code snippet below: <li id="changethis" class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown>LINK</a> <ul class="dropdown-menu"> <li id ...

Records are being loaded into the table, but the browser is unresponsive

After making an ajax call, I am receiving over 1000 tr elements for the tbody of a table. However, when I try to load this data into the tbody of the table, Loading the records into the tbody of the table becomes a problem. $('#loadingRecords') ...

Achieve a stylish layout by displaying three cards per row using Vue.js and Bootstrap 4

I'm facing an issue with my code where I am trying to display Bootstrap cards in rows of three, but the layout is not rendering correctly. It starts with one card, then two, and eventually adds a new column, resulting in some empty spaces with offsets ...

Avoid making redundant web service requests using JQuery AJAX

As I incorporate jQuery into my Classic ASP pages, I'm looking for a solution to prevent users from clicking buttons multiple times and making duplicate server queries. Can anyone suggest an efficient method to achieve this? ...

Guide to retrieving a user's current address in JSON format using Google API Key integrated into a CDN link

Setting the user's current location on my website has been a challenge. Using Java Script to obtain the geographical coordinates (longitude and latitude) was successful, but converting them into an address format proved tricky. My solution involved le ...

Is there a way I can ensure that two elements have identical heights?

Is there a way to ensure that two different elements in HTML are always the same height using CSS? I attempted to achieve this by setting each element to 50vh in the CSS, but it didn't work. codepen: https://codepen.io/ichfickedeinemutterdudummerwich ...

"Customize the number of items displayed per page with Bootstrap Vue's perPage

I am currently working on a Vue project which you can view on codesandbox and utilizing bootstrap-vue. Within the project, there are multiple columns containing cards along with pagination: <template> <b-container> <b-row :cu ...

The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out ...

Unable to resolve the "Error: posts.map is not a function" issue

I am currently developing a social media-like web application. One of the features I'm working on is to display all posts made by users. However, when I run my code, it doesn't show anything and I get an error in the console that says "Uncaught T ...

Issue with Material UI Menu positioning incorrectly when button is aligned to the right or left

When looking at the first image, it appears that the material-UI menu position is working correctly. However, when we change the button position to align-right, the menu position shifts slightly to the left, not perfectly aligning with the right side as in ...

Svelte language switcher experiencing technical difficulties

Currently delving into Svelte 3, I embarked on a project intended to be shared on GitHub in English. However, I realized that some of my friends do not speak English. To accommodate different language preferences, I decided to create a language switcher. H ...

Swipe JS: tap on the edge to view the next item

Currently utilizing Swipe JS to generate a full-screen image gallery and aiming to incorporate the functionality of clicking on the left or right edge to navigate between the previous and next slides. An attempt was made to create absolutely positioned a ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

Saving the name and corresponding value of a selected option element into separate fields using Angular framework

I have implemented the following code to generate a select field. The ngModel is successfully updating the value, but I am also looking to capture the name of the selected option and store it in a different field. Is there a solution to achieve this? ( & ...

Step-by-step instructions for creating a shadow page and displaying a loading div when an ajax call is made

Is it possible to shadow the entire page when a user clicks a button, display a div in the center of the page with a loading gif, and then make an ajax request to a page? If so, can someone explain how to achieve this? I found here, the following code: ( ...