Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure JavaScript fade in and out - fade in not working

Tags:

javascript

See below snippet. Fade out works fine, but any idea why it won't fade in?

My HTML:

  <div id="id10574"><span style="font-size:6em">♥</span></div>
  <button id="b1">Fade Out</button>
  <button id="b2">Fade In</button>
  <script src="fade.js"></script>

and the JS:

var cat = document.getElementById("id10574");

cat.style.opacity = 1;

function fadeout() {
    if (cat.style.opacity > 0) {
        cat.style.opacity = (cat.style.opacity - 0.01);
        setTimeout( fadeout, 10 );
    } else { 

    }
}


function fadein() {
    if (cat.style.opacity < 1) {
        cat.style.opacity = (cat.style.opacity + 0.01);
        setTimeout( fadein, 10 );
    } else { 

    }
}

document.getElementById("b1").addEventListener("click", fadeout , false);
document.getElementById("b2").addEventListener("click", fadein , false);

I'm really stumped on this one. Trying to make a simple effect that will work on IE8 (Sharepoint in corporate environment).

Thanks!

like image 381
user1525612 Avatar asked Mar 16 '15 09:03

user1525612


1 Answers

Basically, cat.style.opacity is a string. So cat.style.opacity + 0.01 would be regarded as a string concatenation.

You can do parseFloat(cat.style.opacity) + 0.01 instead

In fact, there are many ways to coerce a string to number. cat.style.opacity - 0.0 as your fadeout(), or even 1.0 * cat.style.opacity

see https://jsfiddle.net/03rzmyL0/

like image 80
Shuhao Tan Avatar answered Oct 05 '22 04:10

Shuhao Tan