I am learning animations in html / css / js using a code that reproduces a typewriter effect. Everything is working correctly, but I keep getting this error on my console:
**script.js:33 Uncaught TypeError: Cannot read property 'length' of undefined
at StartTextAnimation (script.js:33)
at script.js:37**
I tried some solutions that I found on google but nothing worked. In my console.log(dataText) each string in my array is executed correctly. The error comes at the moment the loop is executed.
This is the code I'm working on now:
document.addEventListener('DOMContentLoaded', function(event) {
// array with texts to type in typewriter
var dataText = ["Cyber", "Sapa", "Synth", "CYBER // SAPA // SYNTH // TÔRTA // POMBADEV.2020"];
// type one text in the typwriter
// keeps calling itself until the text is finished
function typeWriter(text, i, fnCallback) {
// chekc if text isn't finished yet
if (i < (text.length)) {
// add next character to h2
document.querySelector("h2").innerHTML = text.substring(0, i + 1) + '<span aria-hidden="true"></span>';
// wait for a while and call this function again for next character
setTimeout(function() {
typeWriter(text, i + 1, fnCallback)
}, 100);
}
// text finished, call callback if there is a callback function
else if (typeof fnCallback == 'function') {
// call callback after timeout
setTimeout(fnCallback, 700);
}
}
// start a typewriter animation for a text in the dataText array
function StartTextAnimation(i) {
if (typeof dataText[i] == 'undefined') {
setTimeout(function() {
StartTextAnimation(0);
}, 5000);
}
// check if dataText[i] exists
if (i < dataText[i].length) {
// text exists! start typewriter animation
typeWriter(dataText[i], 0, function() {
// after callback (and whole text has been animated), start next text
StartTextAnimation(i + 1);
});
}
}
// start the text animation
StartTextAnimation(0);
});
If anyone can help me I will be very grateful!
PS. Codepen link: https://codepen.io/iMorettini/pen/rNMOvZK
Maybe that dataText[i].length
should be dataText.length
of your line 33
. Because you are checking for the words, not the letters in the words.
would be helpful if you can post a codepen of your project or something similar.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.