I have a div that I’m trying to fade text into.
function fadeIn(divNum) {
let id = null;
fadeDiv = document.getElementById("jsTest");
fadeDiv.innerHTML = "";
console.log(fadeDiv.style.opacity);
if (divNum == 1) {
fadeDiv.innerHTML = "some text";
} else if (divNum == 2 ) {
fadeDiv.innerHTML = "some different text";
} else if (divNum == 3) {
fadeDiv.innerHTML = "still different text";
} else {
fadeDiv.innerHTML = "Oops! that wasn't supposed to happen";
}
clearInterval(id);
id = setInterval(moveIt,100);
function moveIt() {
if (fadeDiv.style.opacity == 1) {
clearInterval(id);
} else {
fadeDiv.style.opacity += 0.1;
console.log(fadeDiv.style.opacity);
}
}
}
<div style="opacity: 0;" id="jsTest"></div>
<button class="boxButtonsb" onmouseover="fadeIn(1)">JavaScript Test</button>
When I mouseover, the opacity only reduces by .1
, and looks like it just loops there forever. The console.log
shows endless 0.1
entries.
But, if I reverse this, so the initial opacity is 1, there’s text in the div to start, and I set fadeIn
to actually fade out, by using fadeDiv.style.opacity == 0
as the if statement check for clearInterfal(id)
, and decrementing fadeDiv.style.opacity
via -= 0.1
, it works correctly.
I’ve zero idea why the decrement is working correctly, and the increment is not.
2
Answers
CSS attributes are always strings, not numbers. Your code is doing
'0.1' + 0.1
which results in'0.10.1'
which isn’t a valid number, so it’s probably getting truncated back to0.1
.One way to change it is to parse the result into a number.
HTMLELement::style
contains string values, needs to be converted to a float: