Opacity effect works from 1.0 to 0, but not 0 to 1.0
-
12-12-2019 - |
Pregunta
I wanted to increase the opacity of a div from 0 to 1.0 on the click of a button. I can decrease opacity from 1.0 to 0.0, but it does not work from 0.0 to 1.0. I also tried using parseInt(element.style.opacity)
and parseFloat(element.style.opacity)
, but none of those work either.
Here's the faulty JavaScript:
function myF(){
var x = document.getElementById("test").style;
x.opacity = parseFloat(x.opacity) + 0.1;
setTimeout(myF(),10);
}
And here's the faulty HTML:
<button onclick="myF()">Click to change opacity</button>
<div style="height:200px; width:200px; background-color:#656b67; opacity:0;" id="test"> </div>
(The following is the javascript and HTML that works for decreasing the opacity)
<body>
<script>
function myF(){
var x = document.getElementById("test").style;
x.opacity = x.opacity - 0.1;
setTimeout(function(){myF();},10);
}
</script>
<button onclick="myF()">Click to resize</button>
<div style="height:200px; width:200px; background-color:#656b67; opacity:1.0;" id="test"></div>
</body>
Solución
Change
setTimeout(myF(),10);
to
setTimeout(myF, 10);
You don't want to call the function immediately, you want to pass it to setTimeout
.
Also, you have a never-ending loop. The function is called recursively, and there is no end condition. When invoking it immidiately, this will cause your browser to freeze.
Otros consejos
function myF(){
var transparent_div = document.getElementById("test");
var opacity = parseFloat(transparent_div.style.opacity);
if (isNaN(opacity)) opacity = 0.1;
else opacity += 0.1;
transparent_div.style.opacity = opacity;
if (opacity < 1.0) setTimeout(function(){myF();},100);
}
If the opacity is set to "" an empty string, you will not be parsing a number, and as such Javascript will return that as a NaN object, which you can test for using isNaN(). I think that is one of your main issues; parseFloat() was the correct thing to use, you just need to check for your return value accordingly.