So, I have created a button on javascript that’s intended to run through a couple of colours with each click. It works but it only goes for the last colour I put, even though I want it to apply these various colours with each click.
The code looks like this:
function colorSwitch(){
mainContent.style.backgroundColor = ‘grey’;
mainContent.style.backgroundColor = ‘green’;
mainContent.style.backgroundColor = ‘blue’;
mainContent.style.backgroundColor = ‘pink’;
}
changeColor.addEventListener(‘click’, colorSwitch);
The project is this throwaway code I made for playing with JS.
You could do an array of the colors, and a variable to keep track of the index you’re going to use next outside the function.
let colorIndex = 0;
function colorSwitch(){
const colors = ['grey', 'green', 'blue', 'pink'];
mainContent.style.backgroundColor = colors[colorIndex];
colorIndex = (colorIndex + 1) % colors.length; // set-up for getting next color
}
1 Like
I tried your solution, and even though I can’t fully understand and break it down, the code works perfectly! I’ll definitely learn arrays as my next JS topic.
I guess you could do it without using an array; you could update the color based on what the background color currently is, but that requires a bunch of if-statements.
function colorSwitch(){
let color = mainContent.style.backgroundColor; // get the current color
// if background-color is grey, set it to green
if (color === 'grey' || color === 'gray') {
mainContent.style.backgroundColor = 'green';
}
// if background-color is green, set it to blue
else if (color === 'green') {
mainContent.style.backgroundColor = 'blue';
}
// if background-color is blue, set it to pink
else if (color === 'blue') {
mainContent.style.backgroundColor = 'pink';
}
// if background-color is pink, set it to grey
else if (color === 'pink') {
mainContent.style.backgroundColor = 'grey';
}
// otherwise, set background-color to grey
else {
mainContent.style.backgroundColor = 'grey';
}
}