Err404r Err404r - 3 months ago 33
Javascript Question

Implementing FadeOut/FadeIn in pure JavaScript

My problem is that only fadeOut works but not fadeIn. I don't use CSS or jQuery for it. And how can I make my code more effective.

The code:

HTML:

<div class="circle"id="circle1"onclick="myFunction()"></div>
<div class="circle"id="circle2" style="visibility:visible" ></div


JavaScript:

function myFunction() {
var element = document.getElementById("circle2");
if (element.style.visibility === "visible") {
var op = 1;
var timer = setInterval(frame, 100)

function frame() {
if (op <= 0.1) {
clearInterval(timer);
element.style.visibility = "hidden";
}
element.style.opacity = op;
op -= op * 0.1;
}
} else {
var op = 0;
var timer = setInterval(frame, 10)

function frame() {
if (op >= 0.95) {
clearInterval(timer);
element.style.visibility = "visible";
}
element.style.opacity = op;
op += op * 0.1;
}
}
}

Answer

There are a few reasons this is not working.

  1. 0 * anything is still 0 so var op=0; and op += op * 0.1 will always be zero.

  2. It is set to hidden not visible while transitioning to fully visible.

I played around with it to make it work but I refactored you code to fit my style while I did it. This is what I came up with.

function myFunction() {

    var element = document.getElementById( "circle2" );
    var op;
    var timer;

    if ( element.style.visibility === "visible" ) {
        op = 1;
        timer = setInterval( fadeOut, 100 )
    } else {
        op = 0.1;
        timer = setInterval( fadeIn, 100 )
    }

    function fadeOut() {
        if ( op <= 0.1 ) {
            clearInterval( timer );
            element.style.visibility = "hidden";
        }
        element.style.opacity = op;
        op -= op * 0.1;
    }

    function fadeIn() {
        element.style.visibility = "visible";
        if ( op >= 0.95 ) {
            clearInterval( timer );
        }
        element.style.opacity = op;
        op += op * 0.1;
    }
}
<div class="circle"id="circle1"onclick="myFunction()">hello</div>
<div class="circle"id="circle2" style="visibility:visible" >Test</div>

Comments