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

Time:11-25

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.

CodePudding user response:

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" >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.

  • Related