Can somebody explain why the following code does not work without the setTimeout?
<html>
<script src="js/jquery.js"></script>
<style>
div {
height:400px;
background-color:red;
opacity:1;
transition:1s;
}
</style>
<div id="foo">toto</div>
<script>
$("#foo").css("transition","0s");
$("#foo").css("opacity",0);
setTimeout(function(){
$("#foo").css("transition","5s");
$("#foo").css("opacity",1);
},1);
</script>
</html>
The script is supposed to reset the opacity of div to 0 then gradually reach maximal opacity in 5 seconds. Without the timer there is no animation : the opacity is 1. I know I could use frames for animation but this was the first thing that goes out of my head at the time and now I'm wondering why this does not work (without the timer)
Working (with timer)
$("#foo").css("transition","0s");
$("#foo").css("opacity",0);
setTimeout(function(){
$("#foo").css("transition","5s");
$("#foo").css("opacity",1);
},1);
div {
height:400px;
background-color:red;
opacity:1;
transition:1s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="foo">toto</div>
Not working
$("#foo").css("transition","0s");
$("#foo").css("opacity",0);
$("#foo").css("transition","5s");
$("#foo").css("opacity",1);
div {
height:400px;
background-color:red;
opacity:1;
transition:1s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="foo">toto</div>