Reputation: 43
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:
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;
}
}
<span id="fadeEl">random starting text</span>
Upvotes: 2
Views: 3511
Reputation: 1870
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" class="text-show">example 1</span>
don't forget your 1-second setTimout
in your function to handle the fade out before you change the text.
Upvotes: 3
Reputation: 22275
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>
Upvotes: 0