Changing the color of individual buttons within a subset of buttons from a larger group of buttons

Is there a way to change the button colors individually when they are clicked?

Requirements:

  1. The default color of the buttons should be grey. Upon first click, they should turn green. After the second click, they should become red. Finally, on the third click, they should revert back to grey.
  2. These buttons are part of a group within a larger group with various colors.

I am currently stuck in JavaScript and unsure how to achieve the desired button color changes (grey, red, green).

Please provide assistance.

var SafetybtnColor = document.getElementsByClassName('Safetybtn');
var Safetybtns = document.querySelectorAll('button.Safetybtn');
SafetybtnColor.onclick = function() {
 
}
<h>Group 1</h>
<div style="position:relative; top:5px" class=Safetybtn>
          <button id="s1">1</button>
          <button id="s2">2</button>
          <button id="s3">3</button>
          <button id="s4">4</button>
          <button id="s5">5</button>
</div>
<br>
<h> Group 2</h>
<div style="position:relative; top:5px" class=QualityIntbtn>
          <button id="qi1">1</button>
          <button id="qi2">2</button>
          <button id="qi3">3</button>
          <button id="qi4">4</button>
          <button id="qi5">5</button>
</div>
          
          

Answer №1

If you're looking to create an array of colors for button interaction, the solution is quite simple. Assign an onclick function to each button to modify the color when clicked.

I made some modifications to your HTML by adding a class to easily identify buttons with this functionality. Additionally, I included a data-* attribute to store the current 'color' value for each button, representing its state.

<h>Group 1</h>
<div style="position:relative; top:5px" class=Safetybtn>
          <button id="s1" class="colorable" data-color="0">1</button>
          <button id="s2" class="colorable" data-color="0">2</button>
          <button id="s3" class="colorable" data-color="0">3</button>
          <button id="s4" class="colorable" data-color="0">4</button>
          <button id="s5" class="colorable" data-color="0">5</button>
</div>
<br>
<h> Group 2</h>
<div style="position:relative; top:5px" class=QualityIntbtn>
          <button id="qi1" class="colorable" data-color="0">1</button>
          <button id="qi2" class="colorable" data-color="0">2</button>
          <button id="qi3" class="colorable" data-color="0">3</button>
          <button id="qi4" class="colorable" data-color="0">4</button>
          <button id="qi5" class="colorable" data-color="0">5</button>
</div>

The implementation in JavaScript is straightforward:

var colors = [
    "lightgray", "green", "red"
];

var btns = document.getElementsByClassName("colorable");
for (idx = 0; idx < btns.length; idx++) {
    var btn = btns[idx];

    btn.onclick = function() {
        var colorIndex = parseInt(this.getAttribute("data-color")) + 1

        if (colorIndex > 2) {
            colorIndex = 0;
        }

        this.setAttribute("data-color", colorIndex);
        this.style.background = colors[colorIndex];
    }
}

You can use RGB values or any other color representation in the colors array. I've kept it simple using names.

Here's a fiddle for demonstration: https://jsfiddle.net/ns56c34u/

Answer №2

To start, remember to enclose your class names in quotation marks. Additionally, keep in mind that button.Safetybtn is not a valid selector since the buttons themselves do not have the class themselves. You should target .Safetybtn button instead, as the buttons are a child of the Safetybtn class. Another option is to use the child combinator > to specify a direct child with .Safetybtn > button.

Once you have selected the group of buttons, it's time to iterate over them using a simple for loop. Inside the loop, set the onclick for each Safetybtns[i], where you can modify the color using the style property and this.style.backgroundColor.

Keep in mind that the actual background color 'grey' for buttons is a specific shade: rgb(221, 221, 221).

You will need an index (e.g., selectedColor) that increments each time a button is clicked. Reset this index to zero once it reaches one less than the number of colors in your loop to restart the cycle.

I'm unsure about your specific requirements, but here's an example that stores the three colors red, green, and grey in an array, switching between them whenever any button is clicked:

var Safetybtns = document.querySelectorAll('.Safetybtn button');

var colours = ['green', 'red', 'rgb(221, 221, 221)'];
var selectedColour = 0;

for (var i = 0; i < Safetybtns.length; i++) {
  Safetybtns[i].onclick = function() {
    this.style.backgroundColor = colours[selectedColour];
    if (selectedColour != colours.length - 1) {
      selectedColour++;
    }
    else {
      selectedColour = 0;
    }
  }
}
<h>Group 1</h>
<div style="position:relative; top:5px" class="Safetybtn">
  <button id="s1">1</button>
  <button id="s2">2</button>
  <button id="s3">3</button>
  <button id="s4">4</button>
  <button id="s5">5</button>
</div>
<br>
<h> Group 2</h>
<div style="position:relative; top:5px" class="QualityIntbtn">
  <button id="qi1">1</button>
  <button id="qi2">2</button>
  <button id="qi3">3</button>
  <button id="qi4">4</button>
  <button id="qi5">5</button>
</div>

I hope this explanation helps! :)

Answer №3

It appears that the solution involves keeping track of a click counter for each button in order to change to a specific color with every click.

One approach is to include a custom attribute like data-clicks="0" for counting, but for simplicity, I will utilize the button's title attribute for storage:

<button id="s1" onclick="this.title=Number(this.title)+1; CycleColor(this.id,this.title)" title="0">1</button>

<button id="s2" onclick="this.title=Number(this.title)+1; CycleColor(this.id,this.title)" title="0">2</button>

<button id="s3" onclick="this.title=Number(this.title)+1; CycleColor(this.id,this.title)" title="0">3</button>

A function needs to be created that each button can call to change its colors...

function CycleColor(Which, ClickNum){
    var B=document.getElementById(Which);

    if(ClickNum=='1'){B.style.background='green';} 
    else if(ClickNum=='2'){B.style.background='red';} 
    else {B.style.background='grey';} 
}

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 there a way to customize the appearance of an unordered list by setting it to display as an image instead of default bullets? I want to

I have been attempting to achieve this desired outcome. However, my efforts to reproduce it resulted in the check marks being rendered at a smaller size than intended due to using an SVG file. An example of this issue can be seen in the following image: I ...

Is it possible to load the content before loading the corresponding images?

With a list of 10 contacts to display, I want the contacts to load first so users can view the information before the corresponding images. The HTML structure is as follows: <table id="contactsTable" data-role="listview" data-dividertheme="c"> < ...

Combine variables within an attribute of an Angular component

I have searched high and low for a solution, but my dilemma persists. Here is my issue: Within my HTML template in Angular, I am trying to pass a series of data to the metadata property of a button. However, I am struggling to concatenate the variable con ...

Is it possible to add a click event to a table row that contains an input checkbox, without interfering with the ability to click the checkbox itself?

I have a table: <table> <tr> <td>Something</td> <td>Something Else</td> <td><input type='checkbox' value='clickme' id='yes'></td> </tr> When a user ...

Utilizing Vue.js to apply conditional statements or filters on v-for generated outputs

Currently, I am working on organizing my results by category. I believe there is room for improvement in the way it's being done: <div><h2>Gloves</h2></div> <div v-for="stash in stashes" :key="stash.id"> <div v-for= ...

Phonegap does not support making multiple SQL requests on the same page

On my webpage, I have various buttons that each trigger different database queries when clicked. One button calls the "queryDB" function to retrieve all data from a table, while another button triggers a query to update the table values. I noticed that th ...

Display a message with `console.log` when a button is clicked in

I would like the console.log to display the coin.id of the element when I click on the row element. import React, { useState, useEffect } from "react"; import { Col, Image, Row } from "react-bootstrap"; import "./Company.scss" ...

Utilizing CSS to smoothly transition elements as they fill in empty space

As I have multiple blocks of content, I slide one to the side and then remove it. Once that is completed, I want the blocks below it to smoothly move up and fill the space. Check out this JSFiddle Example for reference HTML Code <div id="container"&g ...

The concept of an undefined property

I encountered this error in my console: index.js:70 Uncaught TypeError: Cannot read property 'searchForm' of undefined at eval (index.js:70) at Module../src/js/index.js (bundle.js:4245) at __webpack_require__ (bundle.js:20) at e ...

Facing issues when attempting to link two databases using Express

Encountering an issue while attempting to use two Oracle databases simultaneously. My startup function only executes the first connection try-catch block, but displays the console log connection message of the second try-catch block without actually estab ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...

Unleashing the Power of Wildcards in HTML with XPath

When using XPath to extract values from DOM elements, I've encountered inconsistent XPaths. To select all DOM elements on the same level, I've resorted to some wildcard magic. For instance, in an HTML document, my XPaths may look like: //div[@i ...

Introducing the latest issue: "Annotation Not Found" bug detected in flowjs version 0.54.0!

Following the update to flow 0.54.0, the code snippet below is encountering an issue: function runKarmaTest() { const KARMA_CONFIG = {}; return new Promise(function (resolve, reject) { new karma.Server(KARMA_CONFIG, function (exitCode) { ...

I need help with customizing the progress bar in HTML and CSS

How can I create a progress bar like the one shown below: https://i.sstatic.net/BFv87.png .detail-load { height: 42px; border: 1px solid #A2B2C5; padding: 1px; border-radius: 10px; } .detail-load > .detail-loading { ...

Each element in Sass is assigned the same index value in a loop

Seeking to add animations to various div elements with unique delay times, I encountered a puzzling issue. Despite following online tutorials closely (such as this one), the animation delays remain consistent for all divs. The loop I have is as follows: @ ...

Tips for accessing the URL in PhoneGap and parsing the response with jQuery

Currently, I am working on a task in PhoneGap which involves creating a registration page. When the user clicks on the registration page, the values entered will be sent to a specific URL. If the user is already registered or not, the data will be returned ...

Having trouble with PHP upload to server file function

This code seems to be error-free, but unfortunately it is not inserting the file into the database and destination folder upon clicking the upload button. HTML Form <html> <body> <form action="includes/parts-cat/zip ...

Error message "SyntaxError: Unexpected token < in JSON at position 0" encountered while using AJAX

When data is sent through an ajax request and processed, a returned array is encoded into json format. $response = array( 'data' => $leaveData, 'message' => 'Event added successfully', ...

Inserting a vertical barrier in the midst of the content

I am struggling to create a vertical divider and align the text properly in the top right corner of my screen. https://i.sstatic.net/UqURE.png Currently, I am facing issues with displaying the divider and positioning the text correctly. <div class="r ...

Triggering JavaScript Functions with React Button Click Events

I'm struggling to grasp how JavaScript functions interact with React components. I have a "Button" element with an "onClick" event that I want to use to clear an "input" text field. Unfortunately, my attempts haven't been successful so far. Sol ...