I'm having trouble implementing a changing background color on scroll using JavaScript

I've been attempting to change the background color of my navbar on scroll, but I keep encountering this error: 'Uncaught TypeError: Cannot read property 'add' of undefined'. Can someone please help me identify and fix the issue? Here is the CSS class that I'm trying to remove after it scrolls over the first page:

.navbar {
background: transparent !important;
z-index: 10;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
position: fixed;
width: 100%;
}

And here is the CSS class that I'm attempting to add after scrolling into the second page or beyond:

.navbar-active{
position: fixed;
background-color: rgba(0, 0, 0, .692) !important;
box-shadow: 0 3px 1rem rgba(0, 0, 0, .1);
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}

Lastly, here is my JavaScript code to swap out the class lists:

const navbar = document.getElementsByClassName('navbar');

window.onscroll = function(){
const top = window.scrollY;
if(top >= 693){
    navbar.classList.add('.navbar-active');
} else {
    navbar.classList.remove('.navbar-active');
 }
}

Answer №1

Incorrectly accessing the navbar is a common mistake that can easily be avoided by following these steps:

Option One:

const navbar = document.getElementsByClassName('navbar')[0];
Remember that getElementsByClassName returns a list of elements with the specified class name

OR

Option Two:

const navbar = document.querySelector('.navbar');

Your second error lies here:

navbar.classList.add('.navbar-active')
, avoid including a period in your parameter string.

Simplify it like this:

navbar.classList.add('navbar-active')

Answer №2

The issue arises due to the fact that

document.getElementsByClassName('navbar')
returns an HTMLCollection object - which does not have a classList property. This makes sense when considering that multiple elements can share a class, making it illogical to refer to the list of classes for a group of elements instead of just one.

If you specifically want to add or remove a class from a single element, and assuming there is only one element with the class "navbar", you can achieve this in two ways:

const navbar = document.getElementsByClassName('navbar')[0];`

This retrieves the first (and likely only) element with the navbar class, or

const navbar = document.querySelector('.navbar');

which consistently selects the first element matching the given selector. Both methods provide an individual element with the expected classList property.

Another approach would be to use an ID instead of a class - especially if you know the identifier will be unique.

document.getElementById('navbarId')
works well in such cases, as there should only be one element in the document with a specific ID.

Additionally, as mentioned by @MosiaThabo in their response, there is an extra dot at the beginning of the class name you are attempting to add.

Answer №3

When creating a classlist, remember to only include the classnames without using the dot (.) Your code should look like this:

navbar.classList.add('navbar-active');

However, it is highly recommended to use an ID as a selector instead of a class:

#navbar { 
background: transparent !important;
z-index: 10;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
position: fixed;
width: 100%;
}

By doing so, you can easily select it in JavaScript like this:

const navbar = document.getElementById('navbar');

This approach is more efficient for performance reasons.

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

Is it possible that WebdriverIO is unable to retrieve the value for an input

Currently, I am in the process of automating tests specifically for a web application on Safari browser. However, I have encountered some challenges along the way. It appears that webdriverIO is not performing very well with Safari in my environment, which ...

A step-by-step guide on incorporating HTML into a div element with jQuery

<div class="segment"> <div class="segment-inner"> <p>Content Goes Here...</p> </div> </div> <script type="text/javascript"> jQuery(document).ready(function () { jQuery('<i class="fa f ...

Adapting CSS styles according to the height of the viewport

Goldman Sachs has an interesting webpage located here. One feature that caught my eye is the header that appears as you scroll down, with squares changing from white to blue based on the section of the page. I'm curious about how they achieved this ef ...

Building four frames with HTML

I am looking to have four frames set up in an HTML document. However, with the current code provided below, only three frames are being generated. <!DOCTYPE html> <html> <FRAMESET cols="100%" rows="10%,90%" > <FRAMESET rows="100%,"& ...

Error message: Attempting to access property 'create' of an undefined object results in error within react-dates

Encountered an issue while trying to incorporate SingleDatePicker from the 'react-dates' library. Despite attempting various solutions, the error persists. The objective is simply to showcase a calendar and allow users to select dates. Assistance ...

Trouble with punctuation marks causing difficulty in obtaining address information within an Ionic Angular app

I am currently working on a project in Ionic Angular where I need to fetch and display user address details from the backend on an HTML page. The address details consist of three fields: Address line1 (mandatory), Address line2, and Address line3 (non-ma ...

What is causing my webpage to load items, flash, and then suddenly vanish?

I have written this code to fetch data from an API and display it on the screen. Interestingly, when I access localhost:3000, I can see all the information, but it disappears quickly afterwards. There are some warnings appearing in the console that say th ...

Leveraging jQuery within Node.js

Greetings, I am a newcomer here and I hope that my message is clear. My current challenge involves trying to incorporate jQuery into node.js, but unfortunately, all my efforts have ended in failure. I have spent hours attempting to resolve this issue to no ...

A delivery person is sending a JSON post request with an empty body to the Express server

When I sent a POST request from Postman to the Express server, the body is getting parsed correctly using app.use(express.json()), but it returns an empty body. However, I am able to retrieve params and other information successfully. Strangely, it works ...

Validating forms with dynamically populated fields using Jquery

Having trouble with Jquery Validation on dynamically populated fields. In my asp.net project, I need the name fields to remain constant because I split an array of information on the server side and update a database. <form id="insert_additions" action ...

The Ant Design form is not updating values after using setFieldsValue in Testing Library

Currently, I am working with the testing-library/react-hooks library and using renderHook. One issue I'm facing is that I am unable to set a value for my antd form using setFieldsValue. It seems like the value is not being set properly. What could be ...

What is the best method for sending data from the server to a client-side JavaScript file?

Is there a way to send data from the server to a client-side JavaScript file without displaying it on the main screen using the innerHTML property? https://i.sstatic.net/YcsJq.png I've gone through several express.js tutorials but haven't found ...

Is it possible for Ajax to actually make GET requests to the server, and if it does, why doesn't it appear in Firebug?

I have a LAMP setup on my Ubuntu and I am attempting to use Ajax to print the output in an unordered list. However, I am not seeing any results and there are no server calls showing up in Firebug. Here is the HTML file where the call is made: <!DOCTYP ...

Upgrade ngf-select to work with Angular 8 versions

Currently in the process of transitioning from AngularJS to Angular 8. Looking for guidance on how to update the following code snippet for Angular 8: <button class="other-button contactUsSpecific" type="button" (change)="contactCtrl.uploadFile ...

Error encountered when attempting to load image from URL in domain

Why won't the image load on my domain? The image loads fine on other domains, but not mine Is there a problem with my domain? var textureLoader = new THREE.TextureLoader(); textureLoader.crossOrigin = ''; var map = textureLoader.load(&apos ...

Discrepancy in sorting order of key-value objects in JavaScript

Check out my jsFiddle demonstration illustrating the issue: Example Here is the HTML structure: <select id="drop1" data-jsdrop-data="countries"></select> <select id="drop2" data-jsdrop-data="countries2"></select>​ Below is the ...

What is the best way to combine HTML, JavaScript, and CSS in a PHP function file for optimal integration?

how can I properly integrate HTML, JavaScript, and CSS code into a PHP format to place in the function.php file? I have created animations using HTML, JavaScript, and CSS formats, but when trying to add them to a PHP file like function.php, I am facing dif ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window: $scope.displayModalBraintree = function () { $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () { ...