Fade in fade out in javascript

22,486

Solution 1

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. :-)

Solution 2

you could move your fade code to its own function

var alpha = 100
function fade() { 
    if (alpha > 0) {
        alpha -= 1;    
        *your opacity changes*
        (e.g.: .opacity = (alpha/100);
        .style.filter = 'alpha(opacity='+alpha+')';)
    }
    else {
        *complete - modify the click event*
    }
 }

you may want to add .MozOpacity to go with .opacity and .filter. as mentioned in the comments above, though, cancelling or forcing a completed fade may be better than preventing new clicks while the loop's running.

ps: i respect you for coding that yourself. javascript libraries are overused and often unnecessary.

Share:
22,486
Hakan
Author by

Hakan

Updated on July 24, 2022

Comments

  • Hakan
    Hakan almost 2 years

    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>
    
    • Grim...
      Grim... over 12 years
      Can you use jQuery? It makes chaining events very easy.
    • Pritam Barhate
      Pritam Barhate over 12 years
      Why are you writing these by yourself, when a lot of mature javascript animation libraries are out there. For example jQuery has some built in effect. script.aculo.us is another popular JS animation lib.
    • RSG
      RSG over 12 years
      jQuery also implements fadein/out in old versions of IE. Your opacity manipulation will not play.
    • Pritam Barhate
      Pritam Barhate over 12 years
      Or if you want to learn the best way to do it may be you can study the source of these libraries. Most of them are open source.
    • Pete Wilson
      Pete Wilson over 12 years
      Sorry about this "why" comment, but I question whether you really want to make the visitor wait until the animation completes, which might take seconds. When I press the button, I always want the action to take place right now. If your code needs fade to be all done at that time, then you can just force it to be complete. If you've already considered and discarded this idea, I apologize for the detour.
    • Hakan
      Hakan over 12 years
      Thanks for your comments, I just prefer learning the language of javascript :) I just need the fade function on my page, nothing else.
    • kojiro
      kojiro over 12 years
      If you like pain, you could use CSS transitions and fire your code on the transition end event. Right now, this sucks. In the future it will be "the right way".
    • Hakan
      Hakan over 12 years
      Is it bad performance "setting" and "testing" varibales?
    • PHearst
      PHearst over 11 years
  • Hakan
    Hakan over 12 years
    Thanks stackuser10210. I agree with out about libraries. I want to learn javascript before using them.
  • Hakan
    Hakan over 12 years
    Thanks, will have a look :) How can I do it without the quotes in this case?
  • stackuser10210
    stackuser10210 over 12 years
    it's nice to know exactly what your code is doing and to keep things as lightweight as possible, i think. "We know you like programming, so we put a language in your language so you can code while you code." - Fictional jLib : )
  • Hakan
    Hakan over 12 years
    Thanks PPcG, thansk for your answer. I want the function to work in the same way as it does today. If the function is bussy, nothing shall happen, no function i the queu. Maybe my method of "setting" and "checking" variables isn't that bad? Or would you say it't slow down the performance?
  • Marecky
    Marecky over 12 years
    like here isFading = setInterval(function(){changeFading(1);},timer);
  • Hakan
    Hakan over 12 years