Switching the background color of a button on click and resetting the color of any previously clicked buttons (a total of 8

I'm struggling to implement a feature where only one button out of a column of 8 should be toggled yellow at a time, while the rest remain default green. Unfortunately, I can't seem to get the function to execute on click, as none of the colors are changing.

I've been trying to follow a post on How to select and change color of a button and revert to original when other button is clicked as a guide, which has helped me understand querySelectors and changing classes. However, despite my efforts, I can't figure out why my implementation isn't working. When I place Console.log('test') right after the for loop, it fires, but if I put it below onClick, it does not.

JS

for (button in buttons) {
    buttons[button].onclick = function() {
        console.log('test')
        var yellowButton = document.querySelectorAll(".yellow")[0];
        if (this.className == "green") {
            if (yellowButton) yellowButton.className = "green";
            this.className = "yellow";
        }
    }
}

HTML

            <button class="green">UPKEEP</button>
            <button class="green">DRAW</button>
            <button class="green">MAIN</button>
            <button class="green">COMBAT</button>
            <button class="green">MAIN</button>
            <button class="green">END TURN</button>
            <button class="green">CLEANUP</button>

CSS

button{
    width: 100%;
    padding: 10px 20px;
    margin: 3px;
}

.green{
    background-color: green;
}

.yellow {
    background-color: yellow;
}

I'm hoping to achieve a scenario where only one out of the 8 buttons is yellow when clicked.

Answer №1

To simplify the process, instead of toggling between yellow and green classes, you can add a 'highlight' class when a button is clicked and remove it from the previously clicked button.

The 'highlight' class is styled with a yellow background, so when a button is clicked, it adds the highlight class and changes the background to yellow. Clicking on another button removes the highlight class from the first button and applies it to the newly clicked button.

 var buttons = document.querySelectorAll("button");
 
 for (button in buttons) {
    buttons[button].onclick = function() {
        console.log('test')
        buttons.forEach(function(btn){
          btn.classList.remove('highlight');
        })
        this.classList.add('highlight');
    }
}
button{
    width: 100%;
    padding: 10px 20px;
    margin: 3px;
}

.green{
    background-color: green;
}

.highlight {
    background-color: yellow;
}
<button class="green">UPKEEP</button>
<button class="green">DRAW</button>
<button class="green">MAIN</button>
<button class="green">COMBAT</button>
<button class="green">MAIN</button>
<button class="green">END TURN</button>
<button class="green">CLEANUP</button>

Answer №2

Success! I was able to successfully implement your code. Check it out on jsFiddle

Just ensure that you define buttons accurately:

var buttons = document.querySelectorAll(".green");

Answer №3

After some troubleshooting, I discovered that my HTML issue was resolved by relocating the script tag to the bottom of the body. Grateful for the assistance from everyone here!

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

Tips for adjusting the width of the box-shadow in CSS

I am facing a challenge with my button that has a box-shadow effect on hover. Currently, I am unsure how to adjust the width of the box-shadow effect. Here is a snapshot of my button's current appearance: https://i.stack.imgur.com/Mg0df.png</p&g ...

Discover the steps to integrating jsfiddle into my local development environment

If you want to check out the code for this example, head over to jsfiddle at this link. And below is a snippet of the HTML file: <!DOCTYPE html> <html> <head> <script src="http://www.jacklmoore.com/colorbox/jquery.colorbox.js" type= ...

Deactivate radio buttons when the table value is greater than or equal to one

On my webpage, there are radio buttons for 'Yes' and 'No'. When 'Yes' is selected, a hidden <div> appears where users can fill in fields. Upon clicking the 'Add' button, the information is displayed in a table. ...

When entering a sub-URL into the browser address bar, the routes do not display as expected

I am encountering an issue with navigating to different routes within my React application. While the home route is visible and functions properly when I start the app locally (npm run dev), I am unable to access other routes. No errors are displayed in t ...

How can I configure Express to serve Next.js's default 404 error page?

I need to display a default Next.js error page instead of manually sending a 404 response from my Express endpoints when an exception occurs in my endpoint functions. Currently, I am handling errors like this: try { //... } catch(e) { res.status(404). ...

Finding the second through eighth elements in a protractor using a CSS locator

Recently, I have been experimenting with protractor and facing a limitation when trying to reference elements. The only way to refer to them is through CSS, as they only have a class attribute provided. The issue arises when there are more than 7 elements ...

Is there a way to determine the selected radio button using Node.js?

I'm currently working on a form that includes two radio buttons. I am posting the request and using the body parser npm package to retrieve the values of the form inputs. Here is how the radio buttons are implemented in the form: <p> ...

Utilizing a Font Squirrel-provided font within Twitter Bootstrap using LESS styling techniques

I'm currently working on integrating a custom font generated from Font Squirrel as the base font for Twitter Bootstrap (compiled from LESS files). My setup involves Express.js with Node.js, and I have already added the font files to the designated fon ...

The save button click handler is not triggering JQuery Validation

I've been attempting for hours to get the validation working, but without success. I have added the name attribute to the input element and included script sources as well. Even after firing the validate method, the contents are still not being valida ...

CSS image buttons are causing active_link_to list items to disappear when they become inactive

I'm struggling to get the nth css button/list elements to display correctly using active_link_to. The first css button appears without any problems and is active, but when I try to add new buttons to the list, they seem to disappear. HTML <li cla ...

What is the best approach to displaying child nodes in JsTree when they are only generated after the parent node is expanded?

Dealing with multiple children nodes under a parent can be tricky. For instance, when trying to open a specific node using $("#jstree").jstree("open_node", $('#node_27'));, you may encounter an issue where the parent node is not initially open, c ...

Determining WebElement Clickability in Java and Selenium: Beyond the Basics of isDisplayed, isEnabled, and findElement

There is a common method to test if a WebElement is clickable: It typically involves something like this: public static boolean isElementClickable(WebDriver driver, String accessor){ return driver.findElements(By.xpath(accessor)).size() > 0 & ...

Switching URLs or internal pages using jQuery Mobile's select menu feature

Utilizing a select box as the navigation menu for my jQuery Mobile website. Some menu items link to internal pages while others link to external URLs. This is the code I'm using to change the page URL: $('#menu-select').change(function() ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

The use of the `/deep/` combinator in CSS has been phased out and is set to be completely removed

After updating my angular to version 4.0.0 and chrome to 62.0.3202.94, I encountered the following error message: [Deprecation] /deep/ combinator in CSS is deprecated and will be removed in M63, around December 2017. Refer to for more information. The ...

Update the DOM if the index of any data elements have been modified

Can Vue.js detect the swapping of array elements in my data object? data: { list: [ 'Foo', 'Bar', 'Test' ] } This is the method I am using to swap entries: swapIndex: function(from, to) { var first = this ...

Tips for placing the brand logo on the left edge of the Bootstrap 4 navbar

I am facing an issue with the placement of my logo. The code snippet below shows how it currently looks: <nav class="navbar navbar-fixed-top navbar-light bg-primary"> <div class="container-fluid"> <img class="navbar-brand" src="logo.p ...

Using HTML and JavaScript to choose relatives from the extended family: Uncles and Aunts

Looking for a better way to target elements in your HTML code? <div class="chunk" id=""> <div class="chunkContent"> <div class="textLeft" ></div> <div class="textRight" ></div> <div class= ...

Step-by-step guide on fetching blog posts from a Ghost blog by utilizing the API in a Vue cli project

I'm currently working on my Vue cli project and I am trying to showcase all the posts from a Ghost blog using the API. Unfortunately, the example provided on the page is for a nuxt project. Once we have called the dependencies and authenticated with ...

Tips for accessing nested object values in mongoose models

Here's a scenario where I have code written in Node.js using the mongoose module and I'm trying to access nested values. Let me walk you through it: First, I define a Schema: var clientScheme = mongoose.Schema({ name: Object, address: S ...