I want to delay this typing effect after the page loads instead of starting in immediately, how could I do this?
document.addEventListener ('DOMContentLoaded',function(event) {
var dataText = ["This is a typing effect"];
function typeWriter(text, i, fnCallback) {
if (i < (text.length)) {
document.querySelector("h1").innerHTML = text.substring(0, i+1) +'<span aria-hidden="true"></span>';
setTimeout(function() {
typeWriter(text, i + 1, fnCallback)
}, 75);
}
else if (typeof fnCallback == 'function') {
}
}
function StartTextAnimation(i) {
if (typeof dataText[i] == 'undefined'){
setTimeout(function() {
StartTextAnimation(0);
}, 20000);
}
if (i < dataText[i].length) {
typeWriter(dataText[i], 0, function(){
StartTextAnimation(i + 1);
});
}
}
StartTextAnimation(0);
});
Lennholm
7,5301 gold badge23 silver badges32 bronze badges
2 Answers 2
So, it appears you want to delay the start of the animation by a set time after the page has loaded rather than delay it until the page has loaded. We all misunderstood this because the former is a much less common use case than the latter.
You can accomplish this by changing this piece of code:
if (i < dataText[i].length) {
typeWriter(dataText[i], 0, function(){
StartTextAnimation(i + 1);
});
}
... into this:
if (i < dataText[i].length) {
setTimeout(function() {
typeWriter(dataText[i], 0, function(){
StartTextAnimation(i + 1);
});
}, 5000);
}
... for a 5 second delay (5000 milliseconds)
answered Oct 19, 2017 at 17:24
Lennholm
7,5301 gold badge23 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Mason
Sorry, my English is not the best but this worked! and I understand the logic as well, thank you so much!
Mason
Do you maybe also know if I can extend the following opacity animation instead of going straight from 0 to 1 after 1.2 seconds? $("h2").delay(1200).animate({ opacity: 1 }, 700);
Lennholm
@Mason Yes, the delay is, unsurprisingly, the
1200 passed to the delay() method and the 700 is the duration of the animation. Change those values accordingly. Please post a new question if you need more help with that.Put the whole function inside a setTimeout.
document.addEventListener("DOMContentLoaded",function() {
setTimeout(function(){
//do your work
}, 2000);
} );
answered Oct 19, 2017 at 17:33
HariV
7071 gold badge11 silver badges17 bronze badges
Comments
lang-js
, 75(which is a delay of only 75 milliseconds) to a larger value (1 second = 1000 milliseconds).