Tips for changing the color of a button when clicked with multiple buttons present

If I only have one button, changing its color is as simple as this:

<script>
var count = 1;
function setColor(btn, color) {
    var property = document.getElementById(btn);
    if (count == 0) {
        property.style.backgroundColor = "#FFFFFF"
        count = 1;        
    }
    else {
        property.style.backgroundColor = "#7FFF00"
        count = 0;
    }
}

But what if I have multiple buttons and want each to be able to change to any of three possible colors?

Answer №1

let counter = 1;
function changeColor(button, color) {
    let buttons = document.getElementsByClassName("button_class_name");
    for(let i = 0; i < buttons.length; i++) {
          buttons.item(i).style.backgroundColor = "#7FFF00"
    }
}

This function will update the background color of all buttons with the class "button_class_name" to "#7FFF00".

Answer №2

Here's a different approach to achieve the desired result. Use a Toggle feature with three different colors for all buttons. First, create an array of colors. Next, keep track of the number of clicks on each button by adding a data-count attribute to each button element. Then, compare the click count with the color array using this.dataset.count%col.length.

let count = 1;
document.querySelectorAll('button').forEach(function(btn){
btn.addEventListener('click', changeColor)
})

const col = ["#FFFFFF","#AAAAAA","#6A76A7"];
function changeColor() {
this.dataset.count= this.dataset.count >= 0 ? ++this.dataset.count : 0;
   this.style.backgroundColor = col[this.dataset.count%col.length] 
}
<button>one</button><br>
<button>two</button><br>
<button>three</button><br>
<button>four</button><br>
<button>five</button><br>
<button>six</button><br>
<button>seven</button><br>
<button>eight</button><br>
<button>nine</button><br>
<button>ten</button><br>

Answer №3

Perhaps you're in search of something along these lines.

HMTL

<button class="buttons" id="btn-1">Button1</button>
<button class="buttons" id="btn-2">Button2</button>
<button class="buttons" id="btn-3">Button3</button>
<button class="buttons" id="btn-4">Button4</button>
<button class="buttons" id="btn-5">Button5</button>

CSS

.buttons {
  border: none;
  background: transparent;

  padding: 10px 20px;
}

JS

// Alter the color of one button
function setButtonColor(btn, color) {
  btn.css({'background': color});
}

// Adjust the color of a group of buttons
function setButtonsColor(btns, colors) {
  $.each(btns, function (key, value) {
    setButtonColor($(value), colors);
  });
}

$(function(){

  setButtonsColor( $('.buttons'), 'gold')

  setButtonColor( $('#btn-1'), 'red' );
  setButtonColor( $('#btn-3'), 'purple' );

   $('.buttons').click(function(){
     setButtonColor( $(this), 'lightgreen' );
   });

});

Answer №4

If you were to have a collection of ten buttons, you would assign a common class to all buttons and then bind events to each one individually as illustrated below.

 var classname = document.getElementsByClassName("btns");
    var count =1;
    var setColor = function() {
        var button = this;
        if (count == 0) {
            button.style.backgroundColor = this.getAttribute("data-color");
            console.log(this.getAttribute("data-color"))
            count = 1;        
        }
        else {
            button.style.backgroundColor = this.getAttribute("data-color");
             console.log(this.getAttribute("data-color"))
            count = 0;
        }
    };

    for (var i = 0; i < classname.length; i++) {
        classname[i].addEventListener('click', setColor, false);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="button" id="btn1" data-color="#7FFF00" value="btn1" class="btns">
    <input type="button" id="btn2" data-color="#7FFF00" value="btn2" class="btns">
    <input type="button" id="btn3" data-color="#FC0" value="btn3" class="btns">
    <input type="button" id="btn4" data-color="#FFFPPP" value="btn4" class="btns">
    <input type="button" id="btn5" data-color="#FC0" value="btn5" class="btns">
    <input type="button" id="btn6" data-color="#7FFF00" value="btn6" class="btns">
    <input type="button" id="btn7" data-color="#7FFF00" value="btn7" class="btns">
    <input type="button" id="btn8" data-color="#FC0" value="btn8" class="btns">
    <input type="button" id="btn9" data-color="#FFFPPP" value="btn9" class="btns">
    <input type="button" id="btn10" data-color="#FC0" value="btn10" class="btns">

If you wish for each button to have a different color, you can utilize data attributes like data-color='#FC0' and dynamically assign colors based on these attributes. For those with ES6 support, the last line can be replaced with:

Array.from(classname).forEach(function(element) {
  element.addEventListener('click', setColor);
});

Answer №5

Implementing an object-oriented approach can facilitate easy expansion of functionality in the future.

From what I gather, each button is designed to cycle through different colors based on the number of times it has been clicked.

For instance, one click triggers red, two clicks trigger green...

// Testing with only 3 colors and buttons.
// Array of colors
var colorList = ['#f00','#0f0','#00f'];
// Initialize empty array for buttons
var buttonList = [];

// Keeps track of button clicks
var ButtonExtend = function buttonObj(id) {
  this.count = 0;
  if (document.getElementById(id)) {
    document.getElementById(id).addEventListener('click',buttonClick,false);
  }
};

// Function called on button click
function buttonClick() {
  this.style.backgroundColor = colorList[buttonList[this.id].count];
  buttonList[this.id].count++;
  if (buttonList[this.id].count >= colorList.length) {
    buttonList[this.id].count = 0;
  }
}

window.onload = function() {
  // IDs of the buttons
  var buttonId = ['b1','b2','b3'];
  for(x in buttonId) {
    buttonList[buttonId[x]] = new ButtonExtend(buttonId[x]);
  }
}
<button id="b1">button 1</button>
<button id="b2">button 2</button>
<button id="b3">button 3</button>

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

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...

When hovering over certain transitioning elements in a D3JS chart, the animation execution is paused if other elements are also in the process of transitioning

Currently, I have been designing a horizontal bar chart and experimenting with transitions on various elements like rect and circle. The transitions are applied to attributes like width and r to achieve the desired effect. Everything seems to be working fi ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

When a React CSS class is deployed to a production server, it may be automatically

I've encountered a strange CSS issue while working on my React project. One specific section of the JSX <div> has a class with style properties defined in the main .css file. During local development, everything appears as expected. However, aft ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

React slick does not display arrows when there are 4 or more photos

I am facing an issue where the next and previous arrows are not appearing when I have 4 or more photos on react-slick. However, they show up fine when there are 3 or fewer photos. You can view my code at this link: https://codesandbox.io/s/wyyrl6zz3l ...

Exploring jQuery Sortable: Navigating Drag-and-Drop Functionality with Cl

Currently, I am working on developing a menu generator tool, similar to arranging widgets in WordPress but designed specifically for creating menus on websites. I have attempted to build this tool using jQuery and Sortable, along with experimenting with Dr ...

Revamp the table layout for mobile with a unified markup structure

I want to customize the display of my bootstrap table for mobile view. Each row entry should be shown in a separate box or card, similar to the following examples: First: Mark Last : Otto Handle: @mdo Second card- First:Jacob Last:Thornton Handle:@fat Is ...

Can AngularJS support HTML5-mode URL routing in locally stored files (using the file:// protocol)?

Sorry if this question has already been asked, but I haven't been able to find any information on it. I'm working on an AngularJS application that needs to be accessed directly from a hard drive (not through a traditional HTTP server), so the UR ...

I am having an issue with an input field not reflecting the data from the Redux state in my React app,

I am currently working on a todo list project using the MERN stack with Redux for state management. One issue I am facing is that the checkboxes for completed tasks are not reflecting the correct state from Redux when the page loads. Even though some tasks ...

Converting an HTML <img> tag into a Base64 encoded image file: Step-by-step guide

Recently, I made changes to the appearance of an image by adding CSS filters using the "style" attribute of an <img> tag. <img src="myImage.png" style="filter: grayscale(100%)"> As a result, the image now has a different look and I am looking ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code. .event-list .bg{ background:#eee; padding:5px; } .grid .event-list:first-child .bg{ background: #2aac97 } .grid .event-list:nth-child(2) .bg{ backgrou ...

Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that ...

Variable scope not properly maintained when there is a change in the Firebase promise

I am currently working on developing a controller function to handle signup submissions using Firebase. However, I've encountered an issue where the variables within the scope (controllerAs: $reg) do not seem to update correctly when modified inside a ...

Utilizing Mongoose aggregation for counting and grouping operations

I am trying to search for records that correspond to a specific URL but want to return a customized object instead. Here is the model I am working with: const ReactionSchema = mongoose.Schema({ url: { type: String, required: true }, emoji: ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

Animated div or fieldset featuring a multi-step form

I have recently put together a detailed step-by-step guide. Each step is wrapped in its own "fieldset" within a single .html file. To navigate back and forth, I have incorporated javascript into the process. However, as time goes on, I am noticing that th ...

javascript strange behavior observed with multidimensional array

Looking to create a jquery autocomplete input that responds to the user's input from a previous field. I have a php script that returns a json variable, but I'm having trouble setting up my array correctly afterwards. I've attempted settin ...