I made a simple javascript function to change the opacity of a text box. I increment or decrement the CSS opacity property by 0.05 using the set interval function depending on whether the text is to be made visible or hidden. The starting value is 1. So decrementing 0.05 it should reach 0 in 20 intervals. I have set the condition to stop the interval when opacity reaches 0. But it doesn't really stop there and continues to decrease.
let btn = document.querySelector("button[class='opac']")
let box = document.querySelector("div[class='text']")
box.style.opacity = 1
btn.addEventListener("click", () => {
if (box.style.opacity == 0) {
let opacity = 0
let id = setInterval(() => {
opacity += 0.05
box.style.opacity = opacity
if (opacity == 1) {
clearInterval(id)
}
}, 50);
}
else if (box.style.opacity == 1) {
let opacity = 1
let id = setInterval(() => {
opacity -= 0.05
box.style.opacity = opacity
if (opacity == 0) {
clearInterval(id)
}
}, 50);
}
})
If i change the condition to (opacity <= 0), It works but the final value of the opacity is -3.19189e-16. I dont understand why is that the case.