I'm writing a program which I want it to start over, that is, reset to initial value and continue when a certain condition is met. But when the condition is met, the program does not reset to the initial value immediately and start over after two extra steps.
<div>
<div class="box red"></div>
<div class="box green"></div>
</div>
const box = document.querySelector('.box');
const r = 60;
const g = 60;
const b = 60;
let a = 0.1;
let count = 0;
box.addEventListener('mouseover', () => {
if (count <= 10) {
box.style.backgroundColor = `rgba(${r},${g},${b},${a})`;
count++;
a += 0.1;
} else {
count = 0;
a = 0.1;
}
console.log(count);
});
In the image above, I have shown the current output. My condition is fully met at 10, and then I want it to start from 1 again as count and 0.1 as a(opacity), but I am getting 11 and 0 respectively as count when the opacity is not changing before getting to count 1 again and opacity in motion.
I tried using count = 1, but no avail. What have I done wrong here?
You are logging the counter after increasing/resetting it.
Try something like this:
let a = 0.1;
let count = 0;
box.addEventListener('mouseover', () => {
if (count == 10) {
count = 0;
a = 0.1;
}
console.log(count);
box.style.backgroundColor = `rgba(${r},${g},${b},${a})`;
count++;
a += 0.1;
});