Change button colour depending on number of clicks?

Hello,

Does anyone know if it’s possible to change the colour of a button depending on the number of clicks in JS? E.g. one click = red, two = blue etc?

I have tried to google this, but haven’t found exactly what I’m looking for…

It is possible with vanilla js with React or any other library.

Assuming that the admin knows this is not a spoiler answer to a challenge and a code example is required, and they don’t remove this comment,
check this example.

You can have a map to decide the colors and the range:

// Keep a record of the number of clicks
let clicks = 0;

// Prepare a map of colours
const mapColors = {
   five: 'green',
   ten: '#faa500', // orange hex
   other: 'rgb(255,0,0)' // red rgb
};

// Create button and give it a height and width
const button = document.createElement('button');
button.style.width = '100px';
button.style.height = '100px';

// on click logic, increment the clicks record and set the styling based on the number of clicks
button.addEventListener('click',() => {
   clicks += 1;

   if (clicks <= 5) {
    button.style.backgroundColor = mapColors.five;
   }else if (clicks <= 10) {
    button.style.backgroundColor = mapColors.ten;
   } else {
    button.style.backgroundColor = mapColors.other;
   }

   button.textContent = clicks;
});

// Append the button to the body
document.querySelector('body').prepend(button);

This is a humble javascript only example you can run anywhere, even in your browser’s console of any websiet.
For colours you can use hex or rgb/rgba etc.
You can make the map to suite your needs or you can generate colours randomly if you don’t care to specify them.

There are many ways to achieve this, ideally using css classes and html for button.

Excellent, thanks so much. No it’s not a spoiler answer as it’s in relation to a project idea of my own.

This ‘humble’ javascript example is ideal and at that stage I’m at, the ‘humbler’, the better(!). Thanks again for the help.

I’ve got it working and I’m delighted. Maybe this means I like coding (or using other people’s code). Thanks again.

I’ve been using people’s code for over 8 years, I still do it nowadays. Part of the process. Glad it worked for you.

1 Like

I would also like to have this set up so that if the button is clicked more than three times, it goes through the ‘colour cycle’ again (i.e. orig. colour, col1, col2, col3).

There is probably a way a to do this with some type of loop, but I want to figure out if I can do it with the code I have here.

I was thinking about putting, say 'if (clicks = 1, clicks = 4, clicks = 7) etc. but it doesn’t look great and is finite.

Have a go with this.

let clicks = 0;

// Prepare a map of colours
const mapColors = {
  one: 'green',
  two: '#faa500', // orange hex
  three: 'rgb(255,0,0)' // red rgb
};

// Create button and give it a height and width
const button = document.createElement('button');
button.style.padding = '40px';
button.style.width = '100px';
button.style.height = '100px';

// on click logic, increment the clicks record and set the styling based on the number of clicks
button.addEventListener('click', () => {
  clicks += 1;

  button.textContent = clicks;

  if (clicks === 1) {
    button.style.backgroundColor = mapColors.one;
  } else if (clicks === 2) {
    button.style.backgroundColor = mapColors.two;
  } else if (clicks === 3) {
    button.style.backgroundColor = mapColors.three;
    // Reset counter, repeat cycle
    clicks = 0;
  }
});

// Append the button to the body
document.querySelector('body').prepend(button);

thank you. I actually tried that, but then the button stays green all the time

I’ve put it on a pen. https://codepen.io/GeorgeCrisan/pen/dyLRodP

Give it a try there.

Also a version with html and css https://codepen.io/GeorgeCrisan/pen/NWmgqMw (better to focus on the JavaScript part, no clutter)

If you like, add your code to a pen and we can have a look to see why it stays green.

1 Like

thanks very much. I ended up adding a fourth colour (the ‘starting colour’) to the colour map and this seems to be working. Thanks so much for your help.

Hi there,

I had forgotten to post back here about this, but do you know how I might go about applying this function to multiple buttons instead of just one? Maybe you could point me in the right direction?

Sure, I will make a codepen.

@coderostro
I’ve made an example for you here, you can put as many buttons as you like.
It makes use of element dataset property.

I’ve added some code comments to aid with the learning curve but if you have any questions feel free to ask.

Example which works with multiple buttons, each has it’s own state https://codepen.io/GeorgeCrisan/pen/NWmgqMw

Fantastic, great, I’ll take a look.

Much appreciated.

Sorry to bother you again, but I was hoping just to modify the existing code I have (you helped me with that), rather than change it completely.

Is there a way to do that?

I found this forEach snippet online:

// select all the buttons with the class name "btn"
const buttons = document.querySelectorAll(".btn");

// loop through each button and add a click event listener
buttons.forEach(function(button) {
  button.addEventListener("click", function() {
    // do something when the button is clicked
    console.log("You clicked a button");
  });
});

Could I use something like that?

My current codepen is here: