Home > OS >  How to make text fade-out and new text fade in on change
How to make text fade-out and new text fade in on change

Time:10-19

I am trying to make a marquee for my website, however, I am stuck with one thing. I have made it so every 20 seconds the text inside the marquee changes, however, I don't like how the text just changes. I would like to make it so the old text fades out and the new text fades in.

Any help would be greatly appreciated. Relatively new to this :) Here is the script that changes the text:

<span id="fadeEl">random starting text</span>

----

let text = [ "example 1", "example 2", "example 3", "example 4"];
let counter = 0;
setInterval(change, 20000);

function change() {
              document.getElementById("fadeEl").innerHTML = text[counter];
              counter  ;
              if(counter >= text.length) {
                  counter = 0;
              }
          }

CodePudding user response:

you can have two classes in your CSS:

const text = ["example 1", "example 2", "example 3", "example 4"];
let counter = 0;

setInterval(change, 5000);

function change() {
  document.getElementById("fadeEl").setAttribute("class", "text-fade");

  setTimeout(() => {
    document.getElementById("fadeEl").innerHTML = text[counter];
    document.getElementById("fadeEl").setAttribute("class", "text-show");
  }, 1000)

  counter  ;

  if (counter >= text.length) {
    counter = 0;
  }
}
.text-show {
  color: black;
  opacity: 1;
  transition: all 1s ease;
}

.text-fade {
  color: black;
  opacity: 0;
  transition: all 1s ease;
}
<span id="fadeEl" >example 1</span>

then your HTML:

<div id="fadeEl" >Text Here!</div>

now if you change class, it will fade in and out. Just keep in mind you will need to add a 1-second setTimout in your function to handle the fade out before you change the text.

CodePudding user response:

You can also use transitionend event...

const
  marqueeLike = document.querySelector('#marquee-like')
, textList = (function* () { // IIGFE
    const arr = [ 'example 1', 'example 2', 'example 3', 'example 4' ];
    let   idx = -1;
    for(;;) {
      idx =   idx % arr.length;
      yield arr[idx]; 
      yield arr[idx]; 
    }}())
, marqueeChange =_=> {
    marqueeLike.textContent = textList.next().value;
    marqueeLike.classList.toggle('fade-in');    
    };

marqueeLike.ontransitionend = marqueeChange;
// window.addEventListener('DOMContentLoaded', marqueeChange ); // doesn't work with SO snippet...  
setTimeout(marqueeChange, 500 );  // to replace DOMContentLoaded  for SO snippet demo... 
#marquee-like {
  font-family : Arial, Helvetica, sans-serif;
  font-weight : bold;
  font-size   : 20px;
  opacity     : 0;
  transition  : opacity 1s ease;
  }
#marquee-like.fade-in {
  opacity : 1;
  }
<p id="marquee-like"> Text Here! </p>

  • Related