Fade in fade out in javascript

Hakan picture Hakan · Dec 30, 2011 · Viewed 22.3k times · Source

I continue the work on: https://codereview.stackexchange.com/questions/7315/fade-in-and-fade-out-in-pure-javascript

What is the best way to detect if the fade in or fade out is completed before setting a new function. This is my way, but I guess there is a much better way?

I added the alert's to make it easier for you to see.

Why I want to do this is because: If one press the buttons before the for loop has finnished, the animation will look bad.

I want the buttons to work only when the fadeing is completed.

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>

<body>
        <div>
        <span id="fade_in">Fade In</span> | 
        <span id="fade_out">Fade Out</span></div>
        <div id="fading_div" style="display:none;height:100px;background:#f00">Fading Box</div>
    </div>
</div>

<script type="text/javascript">
var done_or_not = 'done';

// fade in function
function function_opacity(opacity_value, fade_in_or_fade_out) { // fade_in_or_out - 0 = fade in, 1 = fade out
    document.getElementById('fading_div').style.opacity = opacity_value / 100;
    document.getElementById('fading_div').style.filter = 'alpha(opacity='+opacity_value+')';
    if(fade_in_or_fade_out == 1 && opacity_value == 1)
    {
        document.getElementById('fading_div').style.display = 'none';
        done_or_not = 'done';
        alert(done_or_not);
    }
    if(fade_in_or_fade_out == 0 && opacity_value == 100)
    {
        done_or_not = 'done';
        alert(done_or_not);
    }

}





window.onload =function(){

// fade in click
document.getElementById('fade_in').onclick = function fadeIn() {
    document.getElementById('fading_div').style.display='block';
    var timer = 0;
    if (done_or_not == 'done')
    {
        for (var i=1; i<=100; i++) {
            set_timeout_in = setTimeout("function_opacity("+i+",0)", timer * 10);
            timer++;
            done_or_not = 'not_done'
        }
    }
};

// fade out click
document.getElementById('fade_out').onclick = function fadeOut() {
    clearTimeout(set_timeout_in);
    var timer = 0;
    if (done_or_not == 'done')
    {
        for (var i=100; i>=1; i--) {
            set_timeout_out = setTimeout("function_opacity("+i+",1)", timer * 10);
            timer++;
            done_or_not = 'not_done'
        }
    }
};



}// END window.onload
</script>
</body>
</html>

Answer

Peter-Paul van Gemerden picture Peter-Paul van Gemerden · Dec 30, 2011

I agree with some of the comments. There are many nice JavaScript libraries that not only make it easier to write code but also take some of the browser compatibility issues out of your hands.

Having said that, you could modify your fade functions to accept a callback:

function fadeIn(callback) {
    return function() {
        function step() {
            // Perform one step of the animation

            if (/* test whether animation is done*/) {
                callback();   // <-- call the callback
            } else {
                setTimeout(step, 10);
            }
        }
        setTimeout(step, 0); // <-- begin the animation
    };
}

document.getElementById('fade_in').onclick = fadeIn(function() {
    alert("Done.");
});

This way, fadeIn will return a function. That function will be used as the onclick handler. You can pass fadeIn a function, which will be called after you've performed the last step of your animation. The inner function (the one returned by fadeIn) will still have access to callback, because JavaScript creates a closure around it.

Your animation code could still use a lot of improvement, but this is in a nutshell what most JavaScript libraries do:

  • Perform the animation in steps;
  • Test to see if you're done;
  • Call the user's callback after the last step.

One last thing to keep in mind: animation can get pretty complex. If, for instance, you want a reliable way to determine the duration of the animation, you'll want to use tween functions (also something most libraries do). If mathematics isn't your strong point, this might not be so pleasant...


In response to your comment: you say you want it to keep working the same way; "If the function is bussy, nothing shall happen."

So, if I understand correctly, you want the animations to be blocking. In fact, I can tell you two things:

  1. Your animations aren't blocking (at least, not the animations themselves -- read below).
  2. You can still make it work the way you want with any kind of asynchronous animations.

This is what you are using done_or_not for. This is, in fact, a common pattern. Usually a boolean is used (true or false) instead of a string, but the principle is always the same:

// Before anything else:
var done = false;

// Define a callback:
function myCallback() {
    done = true;
    // Do something else
}

// Perform the asynchronous action (e.g. animations):
done = false;
doSomething(myCallback);

I've created a simple example of the kind of animation you want to perform, only using jQuery. You can have a look at it here: http://jsfiddle.net/PPvG/k73hU/

var buttonFadeIn = $('#fade_in');
var buttonFadeOut = $('#fade_out');
var fadingDiv = $('#fading_div');

var done = true;

buttonFadeIn.click(function() {
    if (done) {
        // Set done to false:
        done = false;

        // Start the animation:
        fadingDiv.fadeIn(
            1500, // <- 1500 ms = 1.5 second
            function() {
                // When the animation is finished, set done to true again:
                done = true;
            }
        );
    }
});

buttonFadeOut.click(function() {
    // Same as above, but using 'fadeOut'.
});

Because of the done variable, the buttons will only respond if the animation is done. And as you can see, the code is really short and readable. That's the benefit of using a library like jQuery. But of course you're free to build your own solution.

Regarding performance: most JS libraries use tweens to perform animations, which is usually more performant than fixed steps. It definitely looks smoother to the user, because the position depends on the time that has passed, instead of on the number of steps that have passed.

I hope this helps. :-)