How do I get my navbar to change color using a JavaScript scroll function?

I've been struggling with changing the color of my navbar when it's scrolled. I have some JavaScript code at the bottom that should handle this, but for some reason, it's not working as expected. I've double-checked that my bootstrap CDN is updated and that my class references are correct, but nothing seems to be fixing the issue.

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="preconnect" href="https://fonts.googleapis.com"> 
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:ital,wght@0,600;0,800;1,300&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3919c9c878087819283b3c6ddc1ddc1">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <link rel="stylesheet" href="app.css">

    <title> Museum of Candy </title>
</head>
 
<body>
    <nav id="#mainNavbar" class="navbar navbar-dark navbar-expand-md py-0 ps-2 fixed-top">
        <a href="#" class="navbar-brand">CANDY</a>
        <button class="navbar-toggler" data-toggle="collapse" data-target="#navLinks" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"> </span>
        </button>
        <div class="collapse navbar-collapse" id="navLinks">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a href="" class="nav-link">HOME</a>
                </li>
                <li class="nav-item">
                    <a href="" class="nav-link">ABOUT</a>
                </li>
                <li class="nav-item">
                    <a href="" class="nav-link">TICKETS</a>
                </li>
            </ul>
        </div>
    </nav>
    
    <section class="container-fluid px-0">
        <div class="row align-items-center">
            <div class="col-lg-6">
                <div id="headingGroup" class="text-white text-center d-none d-lg-block">
                    <h1 class="">MUSEUM<span>/</span>OF<span>/</span>CANDY</h2>
                    <h1 class="">MUSEUM<span>/</span>OF<span>/</span>CANDY</h2>    
                    <h1 class="">MUSEUM<span>/</span>OF<span>/</span>CANDY</h2>    
                    <h1 class="">MUSEUM<span>/</span>OF<span>/</span>CANDY</h2>
                    <h1 class="">MUSEUM<span>/</span>OF<span>/</span>CANDY</h2>    
                    <h1 class="">MUSEUM<span>/</span>OF<span>/</span>CANDY</h2>   
                </div>
            </div>
            <div class="col-lg-6">
                <img class="img-fluid" src="hand2.png" alt="">
            </div>
        </div>
    </section>

    <section class="container-fluid px-0 content">
        <div class="row align-items-center">
            <div class="col-md-6 order-2 order-md-1">
                <img class="img-fluid" src="milk.png" alt="">
            </div>
            <div class="col-md-6 text-center order-1">
                <div class="row justify-content-center">
                    <div class="col-10 col-lg-8 blurb mb-5 mb-md-0">
                        <h2>MUSEUM OF CANDY</h2>
                        <img src="lolli_icon.png" alt="" class="d-none d-lg-inline">
                        <p class="lead">Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque, iste molestiae...</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <section class="container-fluid px-0 content">
        <div class="row align-items-center">
            <div class="col-md-6 text-center">
                <div class="row justify-content-center">
                    <div class="col-10 col-lg-8 blurb mb-5 mb-md-0">
                        <h2>MUSEUM OF CANDY</h2>
                        <img src="lolli_icon.png" alt="" class="d-none d-lg-inline">
                        <p class="lead">Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque, iste molestiae... </p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <img class="img-fluid" src="gumball.png" alt="">
            </div>
        </div>
    </section>
    <section class="container-fluid px-0 content">
        <div class="row align-items-center">
            <div class="col-md-6 order-2 order-md-1">
                <img class="img-fluid" src="sprinkles.png" alt="">
            </div>
            <div class="col-md-6 text-center order-1">
                <div class="row justify-content-center">
                    <div class="col-10 col-lg-8 blurb mb-5 mb-md-0">
                        <h2>MUSEUM OF CANDY</h2>
                        <img src="lolli_icon.png" alt="" class="d-none d-lg-inline">
                        <p class="lead">Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque, ist...</p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a0a150a0a1f085410093a4b544b4e544c">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="21434e4e55525553405161150f130f10">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
    
<!-- This is the JS section that's not working: -->

    <script>
        $(function () {
            $(document).scroll(function () {
                var $nav = $("#mainNavbar");
                $nav.toggleClass("scrolled", $(this).scrollTop() > $nav.height());
            });
        });
    </script>
</body>

</html>

And here's my custom CSS:

.navbar.scrolled {
    background: rgb(222,192,222);
    transition: background 500ms;
}

I really want the navbar to change its background color on scroll, but no matter what I try, it's just not happening.

Answer №1

I wanted to point out a small error in your code - you mistakenly declared the id as "#mainNavbar", you can simply remove the # from it. id="mainNavbar"

Answer №2

Ensure the removal of the hash from the navigation ID. Refer to the image provided in this link:

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

Dropdown menu in Bootstrap gets cropped behind a scrollable container

I am encountering a problem with my Bootstrap Drop Down. The dropdown is located within a scrollable div with a fixed height. Whenever I click on the dropdown, the menu appears behind the scroll content. However, a normal select works perfectly fine. htt ...

A guide to modifying the color of the Menu component in material-ui

Currently, I am utilizing the Menu component from material-ui and facing an issue while trying to modify the background color. The problem arises when I attempt to apply a color to the Menu, as it ends up altering the entire page's background once the ...

Using JSON encoding to create a new date object with the parameters year (yyy), month (MM), and

I am using a component called chap-tim JS (find it here: ) that requires the following JSON format: data = [ { 'start': new Date(2010, 7, 26), 'content': 'test ' } ]; Althou ...

Aligning a pair of <div> elements within a container in a form field

As I attempt to recreate the survey form challenge from FreeCodeCamp.org Projects, I am facing an issue with aligning two <div> elements inside their parent <div> without the second child moving to a new line using CSS properties other than flo ...

How to eliminate padding between Bootstrap col-xx columns

When using Bootstrap's col-xx classes, the padding can sometimes result in wasted space on smaller screens. To address this, I have decided to remove the padding by nesting col-xx with specific CSS settings like shown below: <style> div[class^= ...

Could the quantity of JavaScript files impact the performance of a project and cause any delays?

In my current HTML and JavaScript project, I am incorporating multiple JavaScript files. I'm curious to learn about the potential impact of having numerous JavaScript files on a web project's efficiency and speed. Can anyone shed some light on th ...

Retrieve the jQuery widget instance by selecting an element within the widget

I am currently developing a widget using the Jquery widget factory. The abbreviated version of the code looks something like this: _create: function(){ this.element.hide(); //hides original input element this.newInput=$("<input>"); //creates ...

C# MVC - Enabling dynamic row addition in an HTML table with multiple fields consolidated into a single cell

Hello, I'm new to c# MVC and could use some guidance. Currently, I am utilizing an example from Matt Lunn (here) to dynamically add new items to a bound list within an HTML table. However, the issue is that all the new items are being added to the fir ...

2-panel accordion interface

Hello there, I've encountered a problem that seems to be related to CSS. Here is the project I'm currently working on: My main focus is on the News accordion menu. The goal is to display a small image (50x50 with padding) next to a large headlin ...

Choose a particular element within an element class using a variable as the selector in jQuery

Is there a way to dynamically add a class to a specific element in an array based on a variable in a for loop, rather than random selection? I need to target elements with the variable provided and possibly apply the class to more than one element if neces ...

Tips for preserving changes made to a jQuery script when the page is reloaded

Is there a way to retain jQuery script changes when the page is reloaded? I have a page where clicking on certain elements triggers events, and I want these changes to persist even after reloading the page, resetting only when the cache is cleared. I appre ...

Develop a unified help document that is compatible across multiple platforms using an existing markdown file

I have been tasked with working on an existing project that already has detailed functionality and relevant information in a markdown file. My goal is to create a universal help file that can be easily viewed on various platforms including Windows, macOS ...

Can jQuery be used to change the functionality of a submit button, such as toggling between show, hide, and submit options?

I am having trouble toggling a button to either submit a form on click or reveal an input field, depending on whether the user clicks outside the input field to hide/collapse it. The issue arises when the user dismisses the input field and the submit butto ...

What is the best way to retrieve the value from a jQuery slider and incorporate it into a form?

I'm facing an issue with a jQuery UI slider that generates a number. However, I can't figure out how to retrieve the slider value in the PHP file when I submit the form. Is there a solution for this? Below, you'll find how the PHP file cap ...

CSS - Customizing the appearance of consecutive child divs

I'm struggling with adjusting the margin between two child divs when they follow each other. The current margin is set at 3rem, but I want it to be 1rem if both child containers have the class "narrow": Is there a way to achieve this without changing ...

Is it possible to create a CSS-only negative border radius?

I'm reaching out for help with a specific issue. I want to create a unique negative border radius for my navigation links, similar to the design shown in this image: http://prntscr.com/9vi0b5 Instead of using images like in the example, I'm look ...

I'm having trouble adjusting the width of my input using percentages with bootstrap, can anyone help me figure out why

Can anyone help me solve a challenge I'm facing with styling my input field without it becoming too large? Currently, when I apply the w-25 class to the input (which sets its width to 25%), the width adjusts based on its original size rather than that ...

Developing AJAX Post Functionality Using Only Vanilla Javascript

Can I achieve AJAX Post in Pure Javascript without using the xmlhttprequest object? Consider a basic form like this: <form action="request.php" id="register_form"> <input type="text" name="first_name" placeholder="First Name"> <input t ...

Is there a way to configure flexbox so that its children wrap in a manner where several children are arranged alongside one specific child

My layout resembles a table using flexbox: +--------------+---------------+-----------------+---------------+ | 1 | 2 | 3 | 4 | | | | | | +---------- ...

Is there a way to prevent this JavaScript code from deleting the initial row of my table?

Looking at the code provided, it's evident that creating and deleting new rows is a straightforward process. However, there seems to be an issue where the default/origin/first row (A-T) gets deleted along with the rest of the rows. The main requiremen ...