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

Using jQuery to adjust the input value up and down with buttons

var number = 1; $("#counter input").attr('value', number); $("#increase").click(function(){ $("#counter input").attr('value', number++); }); $("#decrease").click(function(){ $("#counter input").attr('value', number--); }); ...

What is the method for producing an li and anchor tag using a list object?

Here is the response I received from my web service, and now I need to transform it into a list item tag: {"d":[{"name":"ttt","url":"bbbb"},{"name":"uuu","url":"ppp"}]} How can I create li tags based on the above output? This is the desired format for t ...

Each Browser Approaches Simple Search Fields in its Own Unique Way

In the process of creating a search field with an input field and an svg icon, I encountered different browser behaviors in Chrome, Firefox, and IE11. Chrome – the preferred version Firefox IE11 (confusing) Check out the working demo of the code on c ...

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

Invalid web address entered

While attempting to incorporate a functionality that opens a new window to a specific link when clicking an icon, I encountered an issue where the click action redirects to the wrong URL. Instead of directing to the URL specified in its href attribute, it ...

Tips for concealing the top button on a mat calendar

I have a calendar for a month and year, but when I click on the top button it also displays the day. How can I hide that button or instruct the calendar not to show the days? Check out this image I was thinking of using a CSS class to hide that element. ...

Tips for managing pagination in a Single Page Application

Within my Single Page Application (built with Javascript and AngularJs), I have an items list that is paginated, displaying 10 items per page. To ensure that the user's current pagination remains intact even when navigating to other pages, I store th ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

Delay the loading of JavaScript libraries and multiple functions that are only executed once the document is

After learning how to defer the loading of JS libraries and a document ready function from this post, I encountered a challenge. The code I currently have handles multiple document ready functions inserted by different modules, not on every page. echo&ap ...

Populate HTML dropdown menu with data from an external JSON file

I'm attempting to populate a HTML Dropdown menu with information from an external JSON file, which consists of the following { "Destinations": [ { "destinationName": "London", "destinationID": "lon" }, { "dest ...

What are the best ways to integrate markdown into my Vue.js projects?

Is there a way to utilize markdown within the context of vue.js instead of regular HTML paragraphs? ...

Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here var animals = { flying : {}, underground : {}, aquatic : {}, desert : {} }; To illustrat ...

How to create a Vue.js animated navbar with scroll opacity

I am looking to create a fixed navbar that changes opacity based on user scrolling behavior. Initially, I want the navbar background to be transparent and then transition to white as the user scrolls down the page. An example of what I am trying to achieve ...

Is Nextjs the best choice for developing the frontend code exclusively?

When deciding whether to use Next.js or plain React for my front-end development, should I consider that a back-end already exists? If I am not planning to write a new back-end, which option would be better suited for the project? ...

Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example: <div class="container"> <div class="menu"><p>Text ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Is it possible to transfer the data from the previous row's input to the input of a new row?

Greetings to the StackOverflow community, I am currently utilizing a table form with a specific query: Here is an abridged version of my form structure: <script> $('#addrowbutton').click(function() { $('tr:hidden:first').show(); ...

Is it possible to utilize the HTML5 browser storage on multiple domains simultaneously?

When considering options for HTML5 browser storage such as IndexedDB or Web Storage, it's important to note that the "same origin policy" applies based on what is stated in the specification. Is there a method to store data within the browser that ca ...

The fluid table within the Bootstrap container is not adapting to different screen

Can't figure out why the bootstrap container fluid table is not responsive. Even though I used an example of My First Bootstrap Page that works fine and is responsive, this particular table remains unresponsive. I want to avoid using a scroll but will ...