0

I've created two functions called 'FadeIn' and 'FadeOut' because i can't use jQuery but they don't work, i don't know why. They directly set the opacity to 0 or 1 without doing it gradually. This is the code:

function fadeIn(el){
    var val = 0;
    document.getElementById(el).style.opacity = val;
    function fade(){
        val += .1;
        document.getElementById(el).style.opacity = val;
        if (val < 1){
            setTimeout(fade(), 90);
        }
    }
    fade();   
}

function fadeOut(el){
    var val = 1;
    document.getElementById(el).style.opacity = val;
    function fade(){
        val -= .1;
        document.getElementById(el).style.opacity = val;
        if (val > 0){
            setTimeout(fade(), 90);
        }
    }
    fade();   
}
e-shfiyut
  • 3,538
  • 2
  • 30
  • 31
Edoardo
  • 19
  • 2
  • 2
    Possible duplicate of [Pure JavaScript fade in function](http://stackoverflow.com/questions/23244338/pure-javascript-fade-in-function) – laaposto Aug 17 '16 at 10:09
  • It's likely `style.opacity` gets reported as a string, so you'll first need to parse it to a float to do maths on it. Furthermore, why not just add/remove a class that invokes a pure CSS fade? – Mitya Aug 17 '16 at 10:11

1 Answers1

0

You were very close. when you give fade() instead of fade as the first argument, the function invokes itself, and your setTimeout() does nothing. this should work:

function fadeIn(el){
    var val = 0;
    document.getElementById(el).style.opacity = val;
    function fade(){
        val += .1;
        document.getElementById(el).style.opacity = val;
        if (val < 1){
            setTimeout(fade, 90); // A Small fix to your code
        }
    }
    fade();
}

fadeOut() will be fixed the same way.

e-shfiyut
  • 3,538
  • 2
  • 30
  • 31