I'm trying to have this text fade out on the old text and fade in on the new text

I am trying to have the text fade out but then back in after the new text has changed. I was wondering what might be wrong in my code to where the text appears, then fades out, then back in in a sort of ugly fashion... How can I revise this code? Thank you.

You can view the website that I am working on at http://revolthub.com

<script type="text/javascript">
var text = ['Sometimes you just have to destroy everything in order to build something brand new<span class="period">.</span>', 'So, we decided to destroy the old way of doing things, and completely redesign Revolt<span class="period">.</span>'];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 8000);
$(elem).fadeIn();
function change(){
$(elem).fadeOut();
 elem.innerHTML= text[counter];
    counter++;
    if(counter >= text.length) { counter = 0; }
    $(elem).fadeIn();
}
</script>

Answers 1

  • Replace your change() function with this:

    function change(){
        $(elem).fadeOut(400, function() {
            elem.innerHTML = text[counter];
            counter++;
            if(counter >= text.length) { counter = 0; }
            $(elem).fadeIn();
        });
    }
    

    Explanation: the fadeOut function returns immediately, rather than waiting for the fade to complete. You'll want to pass a callback to fadeOut to make your changes wait until the fade is actually done.


Related Articles