Utilizing HTML, CSS, and JavaScript to dynamically add and remove a class from

I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new button is clicked, the previous one should return to its normal color. My limited knowledge of JavaScript and HTML has made it challenging to pinpoint where the problem lies.

function switchColor() {
  var currentButton = this;
  var allButtons = document.querySelectorAll('.btn');
  
  allButtons.forEach(button => {
    if (button !== currentButton) {
      button.classList.remove('btn2');
      button.classList.add('btn');
    }
  });
    
  if (currentButton.classList.contains('btn')) {
    currentButton.classList.remove('btn');
    currentButton.classList.add('btn2');
  } else {
    currentButton.classList.remove('btn2');
    currentButton.classList.add('btn');
  }
}

document.getElementById('sel').addEventListener('click', switchColor);
/* Your CSS styles here */
<!DOCTYPE html>
<html lang="it">

<head>
  <meta charset="UTF-8>";
  <link rel="stylesheet" href="Normalize.css">
  <link rel="stylesheet" href="Style.css">
  <title>Document</title>
</head>

<body>
  <!-- Your HTML content here -->
</body>

</html>

To address the issue, I have created a JavaScript function called `switchColor()` that removes the colored state from all buttons except the one currently being clicked. The `eventListener` is added specifically to the 'sel' button to trigger this behavior. As you can see, there are some inconsistencies in the way variables are declared, but this is how I have found similar functions implemented online. Please let me know if you need further clarification or assistance.

Answer №1

To achieve the desired outcome, follow these steps:

Start by removing any JavaScript code related to the click listener.

Next, create an array of buttons using this code snippet:

var buttons = document.querySelectorAll('.bottoneCategoria');

Now, add the following function. This function will be triggered whenever one of the buttons is clicked:

function onButtonClick(event) {
    let clickedButton = event.target;

    for (let i = 0; i < buttons.length; i++) {
        buttons[i].classList.replace('btn2', 'btn');
    }

    clickedButton.classList.replace('btn', 'btn2');
}

Lastly, iterate over all buttons and attach the previously created function to each button:

for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', onButtonClick);
}

For more details, refer to the working code snippet provided below.

function hide() {
  var x = document.getElementById("demo");
  var y = document.getElementById("demo2")
  if (x.style.display === "none") {
    x.style.display = "inline-flex";
  } else {
    x.style.display = "inline-flex";
  }
  if (y.style.display === "inline-flex") {
    y.style.display = "none"
  }
}

function hide2() {
  var x = document.getElementById("demo2");
  var y = document.getElementById("demo");
  if (x.style.display === "none") {
    x.style.display = "inline-flex";
  } else {
    x.style.display = "inline-flex";
  }
  if (y.style.display === "inline-flex") {
    y.style.display = "none"
  }
}

var buttons = document.querySelectorAll('.bottoneCategoria');

function onButtonClick(event) {
  let clickedButton = event.target;
  for (let i = 0; i < buttons.length; i++) {
    buttons[i].classList.replace('btn2', 'btn');
  }
  clickedButton.classList.replace('btn', 'btn2');
}

for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', onButtonClick);
}
body {
  font-family: "Open Sans", sans-serif;
  background-color: white;
}

.flex-col {
  display: flex;
  flex-direction: column;
}

/* Other CSS styles here... */
<!DOCTYPE html>
<html lang="it">
... (Your HTML content goes here)
</html>

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

Encountering a Tailwindcss error while attempting to compile the CSS file

Struggling to grasp Tailwind CSS as I try to compile the CSS but keep encountering errors. Despite following numerous tutorials, this persistent error continues to hinder my progress. This is the specific error message that keeps popping up: $ npm run bui ...

The image appears uniquely sized and positioned on every screen it is viewed on

After reviewing the previously answered topics on the site, I couldn't seem to make the necessary adjustments. Despite setting the size and location in the css file, the large image remains centered and fitting for the screen. The "imaged1" class seem ...

Exploring Tabletop.js to retrieve information from an array of data

Issue I am currently attempting to retrieve data from an array that contains two objects. I have implemented Tabletop.js to fetch the data from a public Google Spreadsheet, but I encountered an error in the console stating ReferenceError: object is not de ...

Experiencing issues with the session not functioning properly on the login page

After setting up Centos 6.4 on my HP Server with PHP 5.3.3, Apache 2.2.15, and Mysql 5.1.69, I encountered login issues where it always fails. Here is the source code: index.php <? include "functions.php"; start_session(); session_destroy(); start_ ...

Tips for wrapping and aligning elements in the center

On my website, I have a layout that displays 10 small images (around 100x200 pixels) evenly spaced at the bottom of the page. | | | The wide window la ...

Unveiling the Secrets of Encoding and Decoding JSON within a Concealed HTML

I am in the process of creating a unique control using HTML and JQuery that will showcase a specific text value. Users will have the ability to input various key/value pairs. Here is the current code snippet I am working with: <input id="keyValue" type ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

How to navigate to the "not now" button in Instagram notifications with Selenium and Python

I'm currently working on a custom "Instagram bot" to log in to Instagram. Although I've managed to bypass the login screen, I'm encountering an issue with a popup message that says: https://i.stack.imgur.com/OMA6h.png from selenium import we ...

"Guidance on jQuery syntax: Use a textbox to filter out and hide select options with each keystroke

Is there a way to modify my existing code so that it can show or hide elements based on a filter condition, specifically for Internet Explorer? I want to wrap the unmatched elements in a SPAN tag and hide them if the browser is IE, and vice versa by remo ...

How should text inputs be positioned?

I'm not very experienced with forms, so I'm a bit confused about what's happening here. I'm attempting to position a text input inline with a button, but it doesn't seem to be working. You can view the code I'm using here: htt ...

Quick way to include id="" and class="" attributes to HTML elements using Sublime Text 2

Is there a way to configure Sublime Text 2 where inputting a . (dot) automatically generates class=" " and adding a # (hash) creates id=" " while typing an HTML opening tag? ...

What is the best way to retrieve the background color of specific table cells?

I have a table that showcases various pieces of information. One interesting feature I added is a notes column, which includes a tooltip created using CSS and jQuery. However, there seems to be an issue with the tooltip's behavior - when I hover over ...

Using Sequelize to Link Two Columns Between Tables

In my sequelize database, I have the following table settings: const Accounts = sequelize.define('Accounts', { name: DataTypes.STRING, }); const Transfers = sequelize.define('Transfers', { value: { type: DataTypes.DECIMAL(10, ...

What is preventing the Selenium WebDriver from clicking on elements, despite their presence and focus?

Once again, I am facing a Selenium issue. Last week everything was running smoothly, but today when I attempted to write some new tests, I encountered a strange problem. Every time I try to click on something, Selenium seems to ignore the click. Even wit ...

What is the best way to set up the login page and logged-in homepage using Node, Express, and Passport with the "/" route?

I am currently in the process of developing an application using Node.js, Express.js, and Passport.js. My goal is to create a seamless user experience on the homepage where if you are not logged in, you will see a login form (with potential for additional ...

Using two different typefaces to accommodate two distinct languages on a single webpage

Let me clarify my situation. I want to create a platform where users can input text in both Hebrew and English, regardless of the language of the website itself. This means that users could type in Hebrew on an English website and vice versa. My goal is to ...

Troubleshooting Safari's Issue with onclick() Functionality

I encountered an issue where the code was working perfectly on IE7 but not on Safari (5.0.5). I would like to find a solution without relying on jQuery. The ultimate goal is for this functionality to work seamlessly on iPad, but currently, I am testing it ...

Change the data-theme using jQuery Mobile once the page has finished loading

I am facing an issue with my buttons in a control group that represent on/off functionality. Every time I click on one of the buttons to switch their themes, the theme reverts back once I move the mouse away from the button. How can I make sure that the ...

Unable to retrieve the value property from document.getElementById as it is null

Can someone help me with reading the input field value in my code? <input type="text" name="acadp_fields[1200]" class="text" placeholder="" value="December 26, 1969"> Here is the code snippet I am us ...

How to handle an unexpected token error when using a function within another function in

I'm encountering an issue where the function below is placed above my render function. It doesn't seem to allow me to nest a function within another function. Can you help me identify what's causing this problem? onSelected(i){ this.st ...