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>
3
Answers
Do not modify your
currentIndex (= 2)
, just add flag, that you already printed error out, so your next iteration continues as normal text:I kind of made your code more clear using promises
The problem you are having is that you are simply checking if the
currentIndex === 1
every time. So the first run through it replaces thee
with anx
, and it would just do that every time. Your solution was to manually force the index to2
, which is why the letter is skipped over. Remember, indexes begin at0
!So when you manually force the index to be
2
, that’s the letter right after the firste
, so it was skipped over.So, what I’ve done below is just added a bit of "state tracking" with a
hasTypedError
boolean so that the branch of code that types thex
only runs that first time. I also moved yourcurrentIndex++
to be outside of theif
statement so that it can increment for both branches, and I fixed the manual index reset in theremoveX
function to reset to the correct index now.