I am trying to fade in three separate lines of text, each one delayed slightly later than the last. I have discovered how to fade a single line, and how to delay a single line, but whatever I try cannot combine the two. All the JS research is for .fadeIn('slow') for button selectors and whatever tried doesn't work with the code below . Any advice appreciated.
function showText(id,delay){
var elem=document.getElementById(id);
setTimeout(function(){elem.style.visibility='visible';},delay*1000)
}
window.onload = function(){
showText('delayedText1',1);
showText('delayedText2',2);
showText('delayedText3',3);
showText('delayedText4',4);
}
<h1 id="delayedText1" style="visibility:hidden">First line fades in</h1>
<h1 id="delayedText2" style="visibility:hidden">slightly later this fades in</h1>
<h1 id="delayedText3" style="visibility:hidden">and last this line fades in</h1>
You can take advantage of CSS transitions for this.
Transitions need a numeric value to function, so you can use the opacity
style, rather than visibility
:
function showText(id, delay) {
var elem = document.getElementById(id);
setTimeout(function () {
elem.style.opacity = 1;
}, delay * 1000)
}
window.onload = function () {
showText('delayedText1', 1);
showText('delayedText2', 2);
showText('delayedText3', 3);
showText('delayedText4', 4);
}
h1{
opacity:0;
transition: opacity 0.8s;
}
<h1 id="delayedText1" style="">First line fades in</h1>
<h1 id="delayedText2" style="">slightly later this fades in</h1>
<h1 id="delayedText3" style="">and last this line fades in</h1>