I stripped out everything and placed it in one HTML file so it’s easier to test just this part.
The goal here is for it to first type Wx then remove the x wait for a second, then type elcome.
The code now produces Wlcome, I tried many things but can’t get it to type the **Welcome** with the first e.
Please help
const element = document.querySelector('#typing-area');
let textToType = 'Welcome';
const delayTime = 1000;
const typingSpeed = 100;
let currentIndex = 0;
function typeLetter() {
const currentText = element.innerHTML;
if (currentIndex === 1) {
element.innerHTML += 'x';
setTimeout(removeX, 1000);
} else {
element.innerHTML = currentText + textToType[currentIndex];
currentIndex++;
if (currentIndex < textToType.length) {
setTimeout(typeLetter, typingSpeed);
}
}
}
function removeX() {
const currentText = element.innerHTML;
element.innerHTML = currentText.slice(0, -1);
currentIndex = 2;
setTimeout(typeLetter, typingSpeed);
}
setTimeout(typeLetter, 500);
#typing-area::after {
content: '';
display: inline-block;
width: 0.1em;
animation: blink 1s infinite;
}
@keyframes blink {
50% {
opacity: 0;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Typing Example</title>
</head>
<body>
<div id="typing-area"></div>
</body>
</html>
>Solution :
Do not modify your currentIndex (= 2), just add flag, that you already printed error out, so your next iteration continues as normal text:
const element = document.querySelector('#typing-area');
let textToType = 'Welcome';
const delayTime = 1000;
const typingSpeed = 100;
let currentIndex = 0;
let hasErrorTyped = false;
function typeLetter() {
const currentText = element.innerHTML;
if (currentIndex === 1 && !hasErrorTyped) {
element.innerHTML += 'x';
setTimeout(removeX, 1000);
hasErrorTyped = true;
} else {
element.innerHTML = currentText + textToType[currentIndex];
currentIndex++;
if (currentIndex < textToType.length) {
setTimeout(typeLetter, typingSpeed);
}
}
}
function removeX() {
const currentText = element.innerHTML;
element.innerHTML = currentText.slice(0, -1);
setTimeout(typeLetter, typingSpeed);
}
setTimeout(typeLetter, 500);
#typing-area::after {
content: '';
display: inline-block;
width: 0.1em;
animation: blink 1s infinite;
}
@keyframes blink {
50% {
opacity: 0;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Typing Example</title>
</head>
<body>
<div id="typing-area"></div>
</body>
</html>