After following a tutorial and successfully completing the project, I encountered a JavaScript error saying "Uncaught TypeError: totype[totypeIndex] is undefined". When I tried to log the type of totype[totypeIndex]
, it initially showed as String
, but later changed to undefined
.
Here is my code:
const typedSpan = document.querySelector(".typed");
const totype = ["Fun", "Hard", "Love"];
const delayTyping_char = 200;
const delayErasing_text = 150;
const delayTyping_text = 3000;
let totypeIndex = 0;
let charIndex = 0;
function typeText() {
if (charIndex < totype[totypeIndex].length) {
typedSpan.textContent += totype[totypeIndex].charAt(charIndex);
charIndex++;
setTimeout(typeText, delayTyping_char);
} else {
setTimeout(eraseText, delayTyping_text);
}
}
function eraseText() {
if (charIndex > 0) {
typedSpan.textContent = totype[totypeIndex].substring(0, charIndex - 1);
charIndex = charIndex - 1;
setTimeout(eraseText, delayErasing_text);
} else {
totypeIndex++;
if (totypeIndex >= totype.length)
totypeIndex = 0;
setTimeout(typeText, delayTyping_text);
}
}
window.onload = function() {
setTimeout(typeText, delayTyping_text);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #111111;
font-family: monospace;
color: #ffffff;
text-align: center;
}
.wrapper {
height: 100vh;
width: auto;
display: flex;
justify-content: center;
align-items: center;
}
.effect-wrapper {
text-align: center;
font-weight: normal;
}
.typed {
font-weight: bold;
color: #00bdff;
}
.cursor {
display: inline-block;
background-color: #b0ff95;
animation: blinker 800ms infinite;
}
.cursor.typing-true {
animation: none;
}
@keyframes blinker {
0% {
background-color: #b0ff95;
}
50% {
background-color: transparent;
}
100% {
background-color: #b0ff95;
}
}
<div class="wrapper">
<h1 class="effect-wrapper">Coding is <span class="typed"></span> <span class="cursor"> </span></h1>
</div>
If anyone knows how to fix this error, please let me know. Thank you!