How can I fade text out and then in with JS and/or CSS?

Issue

I have a webpage where, when the user clicks on a button, it selects a random haiku from a dataset and displays it.

I’d like that when the user clicks the button, the text would first fade out, then change to the new haiku and then fade in again but I can’t get this to work.

I’ve tried doing this the following way. The text has the following CSS class:

.text-fade{
    transition: opacity 1s;
}

And I can get the text to fade before changing the haiku this way:

document.getElementById('haikuButton').addEventListener('click', () => {            
    document.getElementById('haikuText').style.opacity = 0;
    setTimeout(getRandomHaiku, "1000"); //this function picks the random haiku from the set and asigns it after the text has faded
});

But I don’t know how to get it to fade in, if I do something like this:

document.getElementById('haikuButton').addEventListener('click', () => {            
    document.getElementById('haikuText').style.opacity = 0;      
    setTimeout(getRandomHaiku, "1000"); 
    document.getElementById('haikuText').style.opacity = 1;      
});

Nothing happens, I assume because it all happens instantly, the opacity is set to 0, the text chosen and then the opacity set again to 1, the function ends and so there is no way to see the fade.

Solution

You need a setTimeout on the actual change in opacity. Your timeout is just on fetching the haiku.

const button = document.getElementById('haikuButton');
const text = document.getElementById('haikuText');

button.addEventListener('click', () => {
  fadeOut();
  setTimeout(fadeIn, "1000");
});

function fadeIn() {
  text.style.opacity = 1;
}

function fadeOut() {
  text.style.opacity = 0;
}
.text-fade{
    transition: opacity 1s;
}
<button id="haikuButton">
  <span id="haikuText" class="text-fade">TEST</span>
</button>

Your code is basically saying:

  • "Hey, fetch a haiku in x amount of millis…"
  • "Now, change opacity…"

The setTimeout doesn’t make all code coming after it wait for it to run.

Answered By – H3AR7B3A7

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published