The error occurred at line 12 in the app.js file, where it is unable to access properties of an undefined object, specifically the 'className' property. This occurred within an anonymous function in an HTMLDivElement

I am facing an issue with my website where I have buttons on the right side. I want to use JavaScript to change the style of the button when it is clicked. When the page loads, the home button should have a background-color: green. However, when another button is clicked, the home button's background-color should change to black/gray. The button that was clicked should remain black/gray, and there should be no error in the console. But, if you click any other button after the first click, the background-color will stay gray/black and an error will appear in the console:

app.js:12 Uncaught TypeError: Cannot read properties of undefined (reading 'className') at HTMLDivElement.<anonymous> (app.js:12:53)

The following code is being used:


const sections = document.querySelectorAll('.section');
const sectBtns = document.querySelectorAll('.controls');
const sectBtn = document.querySelectorAll('.control');
const allSection = document.querySelector('.main-content');

function PageTransitions() {
    // Button click active class
    for (let i = 0; i < sectBtn.length; i++) {
        sectBtn[i].addEventListener('click', function() {
            let currentBtn = document.querySelectorAll('.active-btn');
            currentBtn[0].className = currentBtn[0].className.replace('active-btn', '');
            this.className += 'active-btn';
        })
    }
}

PageTransitions();

This issue prevents the background color from changing. Any suggestions on how to resolve this would be greatly appreciated. Thank you!

Answer №1

You've followed all the steps correctly, but remember to add a space when giving a class name.

In your JavaScript code:

Instead of this.className += 'active-btn';

You should use this.className += ' active-btn';

Just a simple space "__"

Now everything should be working smoothly!

Answer №2

To update this line this.className += 'active-btn'; with

sectBtn[i].classList.add("active-btn")

The rationale behind this change is that the "this" keyword refers to the current class object or functionality, but in this scenario, you need to select the button you are clicking on and add a class to that specific button. Therefore, we utilize classList to append a new class to the HTML element.

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

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

Can you explain the distinction between browser.sleep() and browser.wait() functions?

Encountering timing problems with my protractor tests. Occasionally, test cases fail because of network or performance-related issues. I managed to resolve these issues using browser.sleep(), but recently discovered browser.wait(). What sets them apart an ...

Issue: Trouble with Rotating Tooltips in Javascript

I am facing a challenge with the tooltips on my website. I want to ensure that all tooltips have a consistent look and transition effects, but I am struggling to achieve this. The rotation and other effects applied using javascript are not functioning prop ...

HTML/JS Linking Tool

I'm new to HTML and JavaScript, coming from a background in Python. I'm working on a program where you enter a link into an HTML form and when you click a button, it's supposed to take you to that link. However, when I click the button, the ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

dealing with a situation where the call to the getElementsByTagname method returns null

Here is a snippet of JavaScript code that I am working with: <script language="JavaScript" type="text/javascript"> var sendReq = getXmlHttpRequestObject(); var receiveReq = getXmlHttpRequestObject(); var lastMessage = 0; var mTimer; ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Header Stability TransitionAndView

I'm not very experienced with JavaScript, so please bear with me. I'm attempting to create a fixed header that transitions to 50% opacity when scrolled down and returns to full opacity (opacity: 1.0) when scrolled back to the top. Here is my cur ...

Unforeseen rotation happening in CSS animation

I find myself struggling with my math skills from junior high. My goal is to rotate two divs around the Y axis in opposite directions. I have set up two animations for this purpose: @-webkit-keyframes first{ 0% { -webkit-transform: rotateY(0); } ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

Steps for creating new users using a post request

I've been working on developing a chat application using react-chat-engine, and everything is running smoothly except for one issue - I'm struggling to figure out how to send a post request to create new users. Below is the code snippet I'v ...

Using Vue.js to dynamically update values in JavaScript code or tags

I've encountered an issue that I'm having trouble articulating, but I'll do my best to explain. Upon loading the page, the following code snippet, which uses jinja-based placeholders, is executed: <div class="ui container"> ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

Encountering an unexpected or invalid token in line 1 after reinstallation of Windows can be a frustrating experience

Yesterday, my JavaScript file was running smoothly. However, after reinstalling Windows and Node, I'm encountering an error when trying to run the same JavaScript file today. $ node index.js C:\Users\<user-name>\Google Drive&bsol ...

Passing HTML element values to Python in Odoo 10: A complete guide

I am working on an Odoo module that includes an Html <select> tag. I need to pass the value of the <option> (within the select tag) to a Python model so that I can perform certain actions based on this value. Can anyone provide guidance on how ...

Methods for dynamically populating dropdown lists with JavaScript and Bootstrap

I have collected all 387 regions for the current date and now I want to dynamically populate a bootstrap dropdown with these regions using JavaScript. Below is the basic HTML code for a bootstrap dropdown: <div class="dropdown"> <button class ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

The issue with window.addEventListener failing to update state when the scrollY is not at zero persists during route changes

When using addEventListener in the componentDidMount lifecycle method to add a class to a header based on the scroll behavior, an issue arises when changing routes via a modal or browser back button. The scrolling state is not accurately reflected as the s ...

Dropdown selection in Angular 4 with Firebase integration

I'm currently using Angular 4 in conjunction with Firebase to create a dropdown selector for a list of properties. Upon selecting a property from the dropdown menu, I expect the location of that property to be displayed in another input field below. ...