Build six squares with no color
Every time you click one, it turns green
When the last square turns green, they all go back to no color in backwards sequence to which it was clicked (not all at once)
const buttons = document.querySelectorAll(".square");
for (const button of buttons) {
button.addEventListener("click", UpdateSquares);
}
let array_sqr = [];
function UpdateSquares(event) {
const btn = event.target;
btn.style.backgroundColor = 'green';
array_sqr.push(btn.id);
if (array_sqr.length == 6) {
ReverseSquares();
}
}
function ReverseSquares() {
array_sqr.reverse();
for (const [index, id] of array_sqr.entries()) {
const reverseBtn = document.getElementById(id);
setTimeout(() => {
reverseBtn.style.backgroundColor = 'white';
}, index * 1000);
array_sqr = [];
}
}```
2
Answers
You have some errors here:
array_sqr
directly. You don’t need to useid
attribute for that.array_sqr
inside the for loop, you should do it after the loop. Though it works because thefor
loop still uses an iterator from the old array value it looks bad, and there’s no need to assign a new empty array value several times while iterating.for
loop withArray::forEach()
to make it more compact and clear and avoid that problem with assigningarray_sqr
.array_sqr.length == buttons.length
check to allow any number of buttons in the future.ReverseSquares()
isn’t reused anywhere there’s no need in it – just make the code inline.