Increment opacity of an element

Asked

Viewed 71 times

5

My fadeOut is ok, but the fadein isn’t working...

function fadeIn(elem, speed)
    {

    if(!elem.style.opacity)
    {
        elem.style.opacity = 0;
    }
    InInterval(function(){

 elem.style.opacity += 0.03;

    }, speed /100);
}

1 answer

4


The problem is that the opacity value is interpreted as a string (text), not as a number. You can do thus:

function fadeIn(elem, speed) {
   if(!elem.style.opacity) {
      elem.style.opacity = 0;
   }
   timer = setInterval(function(){
      if(parseFloat(elem.style.opacity) >= 1) clearInterval(timer);
      elem.style.opacity = parseFloat(elem.style.opacity) + 0.03;
   }, speed / 100);
}

ele = document.getElementById('hey');
fadeIn(ele, 5000);
#hey {
  background-color: red;
  width: 100px;
  height: 100px;
}
<div id="hey">

</div>

  • it already works, thank you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.