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

Issue occurs when a circle element is not following a div element on mouse

Currently, I have implemented some jQuery code that instructs a div named small-circle to track my cursor movement. I discovered how to accomplish this by referencing a thread on stack overflow. I made slight modifications to the script to suit my specifi ...

If the PHP function does not exist in jQuery, then take action

I am currently utilizing a form that activates a PHP function through jQuery in the following manner: jQuery('#subnewtideform').submit(ajaxSubmit_subnewtideform); function ajaxSubmit_subnewtideform(){ var subnewtideform = jQuery(this).seri ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

Currently seeking assistance in replacing an existing Wordpress object with a new one

I'm looking to swap out the current slider image with a new slider. Whenever I try to replace it with the TOP 5 Games, they disappear or don't show up at all. <?php if( function_exists('cyclone_slider') ) cyclone_slider('24&ap ...

What sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...

Can a Dashcode Webkit Web app be transformed into traditional HTML and CSS?

I have developed a blog using Dashcode, incorporating HTML, CSS, and Javascript to pull data from an xml file. It's pretty simple... My perspective on this is: 1. JavaScript should be compatible with all browsers (with some variations). 2. I may need ...

Obtain the data from the hyperlink destination

Having some trouble extracting a value from an href link to use in my database operations. Unfortunately, I couldn't retrieve the desired value. Displayed below is the code for a button: <a class="btn btn-info" href="scheduleSetTime.php?id=&apo ...

The setInterval() function is not functioning properly when used with PHP's file_get_contents

Currently, I'm encountering an issue while attempting to use the function get_file_contents() within a setInterval(). The objective is to continuously update some text that displays the contents of a file. Below is the code snippet: <script src="h ...

CSS swapping versus CSS altering

Looking to make changes to the CSS of a page, there are two methods that come to mind: Option 1: Utilize the Jquery .css function to modify every tag in the HTML. For instance: $("body").css("background : red") Alternatively, you can disable the current ...

Ways to establish a minimum height for material cards using Material UI

I am facing an issue with a card that contains a nested table. The card expands and shrinks based on the size of the table inside it. I want to prevent the card from shrinking when the table has no data or just one entry. Instead, I need the card to mainta ...

Ways to Implement Horizontal Scrolling in Dojo FilteringSelect Component

The select field on my form contains option values that are over 250 characters long, making it difficult for users to read them within the select box. Is there a solution to make the select field scroll horizontally or wrap the lengthy text? ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

Tips on disregarding events within an html table

I have a see-through table with a width set to 100% that houses various HTML content. I am utilizing the table to properly center a particular element on the screen. However, the table is intercepting mouse events and preventing users from clicking on lin ...

Difficulty with the increment of my counter when using addeventlistener

I'm currently facing a challenge that I can't seem to figure out... Here is the issue (in JavaScript): export default { name: "TodoList", data() { return { title: "", content: null, isDone: true, count: 0, n ...

Preserve line breaks within HTML text

Utilizing the powerful combination of Angular 5 and Firebase, I have successfully implemented a feature to store and retrieve movie review information. However, an interesting issue arises when it comes to line breaks in the reviews. While creating and edi ...

Adjust the dimensions of the icon

My current project involves creating a sidebar with icons and associated text to represent each icon. However, I encountered an issue while trying to adjust the size of the icons within the sidebar using the "useStyles()" method. For some reason, the size ...

Encountering a configuration file issue when attempting to consume a WCF service using an Ajax

Currently, I am encountering an issue when trying to consume a WCF service using jQuery. The error message I received is "Configuration binding extension 'system.serviceModel/bindings/webHttpbinding' could not be found. Verify that this binding e ...

Having trouble with $.post request to a different domain in a node.js/express app running on port 8081

Whenever I try to use $.post, I keep getting the error message POST https://thewebsite.com 400 (Bad Request). Here is the code snippet that's causing the issue: $.post("https://website.com/blabla", { domain: "infoinfo.com", room: "someInfo", ap ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display. HTML structure: <div id="canvas"></div> To populate the canvas with div elements, I'v ...