The color of my Navbar remains stationary despite implementing Javascript for scroll effects

I am having trouble with the Javascript portion of my code, which I copied from a tutorial. The Navbar is not changing color when scrolled, and I'm not sure if the issue lies with the Javascript, the CSS, or if I need to add 'scrolled' to the Navbar class as well. Any help would be appreciated. Thank you.

<!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.0/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.0/js/bootstrap.min.js"></script>
<script>
$(window).scroll(function(){ $('nav').toggleClass('scrolled', $(this).scrollTop() > 1080);
}); 
</script>
<style>
  navbar.scrolled{
    background-color: darkgray !important;
  }
</style>
</head>
<body>
 
<header>
  <div class="container-fluid">
    <div class="navbar navbar-light navbar-expand-md fixed-top">
      <a class="navbar-brand" href="#">Brand</a>
      <button class="navbar-toggler" data-toggle="collapse" data-target="#uniqueIdentifier">
                    <span class="navbar-toggler-icon"></span>
                </button>
      <div id="uniqueIdentifier" class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link" href="#">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Skills</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <div class="content" style="height:200vh;"> 
  
  </div>
 </header>
 
</body>
</html>

Answer №1

To ensure your event listener is registered once the DOM has loaded, place your script tag at the bottom of the body. Additionally, make sure you are targeting the correct DOM element in your CSS/jquery code.

<!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.0/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.0/js/bootstrap.min.js"></script>
    <style>
      div.navbar.scrolled {
        background-color: darkgray !important;
      }
    </style>
  </head>
  <body>
    <header>
      <div class="container-fluid">
        <div class="navbar navbar-light navbar-expand-md fixed-top">
          <a class="navbar-brand" href="#">Brand</a>
          <button
            class="navbar-toggler"
            data-toggle="collapse"
            data-target="#uniqueIdentifier"
          >
            <span class="navbar-toggler-icon"></span>
          </button>
          <div id="uniqueIdentifier" class="collapse navbar-collapse">
            <ul class="navbar-nav ml-auto">
              <li class="nav-item">
                <a class="nav-link" href="#">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Skills</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="content" style="height:200vh;"></div>
    </header>
    <script>
      $(window).scroll(function() {
        $("div.navbar").toggleClass("scrolled", $(this).scrollTop() > 1080);
      });
    </script>
  </body>
</html>

Answer №2

To ensure the script functions properly after the DOM has finished loading, it should be inserted at the end of the body tag.

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

Display the file name of the following/preceding images on the backward/forward button

Hello, I am fairly new to web development and could use some professional assistance. I have a slideshow set up, but I am struggling with adding the filename of the next or previous images to the back/forward icons of the slideshow. Is this achievable with ...

When developing a website in Sitecore 8, the link consistently opens in a new window rather than a new tab, even after including the target="_blank" attribute

When using Sitecore-8 CMS, external links are set to open in a new window instead of a new tab in Internet Explorer 10 and IE 9, even when target="_blank" is included in the href tag. We are seeking a solution to address this issue. Any assistance would b ...

Please hide the dialog UI when the area outside of it is clicked, as demonstrated in the example

$(function() { $( "#dialog" ).dialog({ autoOpen: false, show: { effect: "blind", duration: 2000 }, hide: { effect: "explode", duration: 500 } }); $( "#opener" ).click(function() { ...

Unidentified variable in Angular Ajax function when accessed outside its scope

Currently, I am in the process of creating a ticket admin table. However, I am facing some challenges with exporting a variable outside of an ajax function. Here is my code: app.controller('bodyController',function($scope,$http,$sce){ $scope.ti ...

What is the best way to incorporate TypeScript into a simple JavaScript project and release it as a JavaScript library with JSDoc for TypeScript users?

Issue: I have encountered difficulties finding an efficient solution for this. Here's a summary of what I attempted: To start, ensure that allowJs and checkJs are both set to true in the tsconfig.json, then include the project files accordingly. Ty ...

Asynchronously parsing CSV files in NodeJs using the `await` keyword within the `on('data')`

I have a specific code snippet that is designed to read lines from a .csv file one by one and then store each processed row into a database const csv = require('csv-parse') const errors = [] csv.parse(content, {}) .on('data', async ...

What is the best way to ensure DIVs or SPANs have a fixed width with their content while also utilizing the remaining available space with white space?

My current setup is similar to the following. <div width="100%"> <span width="33%">FIRSTNAME</span> <span width="33%">|LASTNAME</span> <span width="33%">|CITY</span> </div> When executed, it appears a ...

Ways to modify the default text in a dropdown menu?

I'm currently attempting to modify the title of a dropdown using the Multi-select plugin found here. However, I've encountered an issue where I am unable to dynamically change the text (Dropdown title) of the dropdown using JavaScript. $(' ...

Is there a way to close the menu in react by clicking anywhere on the

Presently, I have a solution to close my topbar menu that involves clicking the menu icon. However, this method is not satisfactory because it only closes the menu when the icon is clicked. I am looking for a way to make the menu close when any area of th ...

Troubleshooting ng-click not functioning within ng-repeat with database integration in MEAN Stack

//app.js var blogApp = angular.module('BlogApp', []); blogApp.controller('BlogController', function($scope, $http){ $scope.createPost = createPost; $scope.deletePost = deletePost; function init(){ getAllPosts(); } init(); ...

Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section locat ...

The grid flex end is behaving differently than I anticipated

I am struggling to align two buttons vertically on the right side. Here is my code snippet: const WalletsContainer = () => { return ( <Grid style={{ background: 'red' }} direction={'column'} alignItems={'flex-end'} ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

What is the method for transferring a script-defined variable to a division tag in an ASP.NET MVC5 Razor view?

I am looking to pass the value of the target from a script to a division tag in MVC. Below are the codes I have implemented. Script: @section Scripts{ <script type="text/javascript"> $('a[data-toggle="tab"]').on('show ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

Does defining the width and height of images go against the principles of material design?

Currently, I am immersed in a project utilizing material design. In this context, I find myself contemplating the size of an image that has been hard-coded as (200x200). I am curious to know if this approach aligns with the principles of material design. ...

Styles and CSS have been successfully loaded, however, the content is not appearing

After attempting to import a web HTML CSS template into my self-made MVC, I encountered an issue. While the template works properly on its own, it fails to connect to the CSS files and display proper styles when accessed through my controller. Instead, onl ...

How to Use Radio Buttons in Material-UI to Disable React Components

Just starting out with ReactJS and Material-UI, I've been experimenting with them for about 3 weeks. Currently, I'm facing a challenge where: - There are 2 radio buttons in a group and 2 components (a text field and a select field); - The goal is ...

Applying a transparent layer to all slider images, with the exception of the one that is

I am utilizing an IosSlider that is functioning properly, but I am looking to enhance it by adding opacity to all images except for the selected image. This adjustment will make the selected image stand out more and enable users to focus on one image at a ...

Node.js client-side code

Hi all, I am currently exploring Nodejs and experimenting with setting up a server-client connection using sockets. The server side seems to be functioning properly, but I am encountering some difficulties with the client side connection. I would appreciat ...