Skip to content

Randomize color pairs onclick (CSS, JavaScript)

There is a button on my website that should change the page’s background color and the headline text color onclick (simultaneously). What makes it more complex is that the possible color pairs (BG + headline) should be pre-determined, but the pairs themself should be randomized, so each time you click the button you randomly get one of the possible color pairs. Also one should not get the same color pair twice in a row.

How do I do that?

Answer

actually your question already gives the answer you want. the logic you have in describing the problem is correct, so it’s just a matter of implementing it into a line of code. And based on the problems above, here are the results of my problem solving.

1. create a list of colors with an array

let color = ['red','green','blue','yellow','purple','pink','azure']

2. take the button element

const button = document.querySelector('.btn');

3. implement the logic when the button is clicked

button.addEventListener('click', () => {
  let pickRandomColorP = Math.floor(Math.random()*color.length);
  document.body.style.background = color[pickRandomColorP]
})

you could visit the working example via codepen in this link