I have a problem in my following Code:
let textPos = document.getElementById('js-headline');
let i = 0;
function typewriter() {
let letters = ['C', 'o', 'd', 'e', 'X'];
if (i < letters.length) {
textPos.innerText = letters[i];
i ;
setTimeout(typewriter, 1000);
} else if (i == letters.length) {
let lastLetter = letters[letters.length - 1];
lastLetter.style.color = 'red';
}
}
typewriter();
in my "else if" I select the last element of my array and I like to change the color but it doesn't work - I get an error message
"Uncaught TypeError: Cannot set properties of undefined (setting 'color')".
And one thing is crazy, I can put the last element of this array in an alert Box or in a console.log and it shows me the last element...
CodePudding user response:
You're trying to set the .style.color
property of a string, which is impossible. You need to make a <span>
element to be able to change the color, and add the <span>
instead of the letter itself.
Also, your conditionals for finding the last element is wrong, so I fixed that too.
let textPos = document.getElementById("js-headline");
let i = 0;
function typewriter() {
let letters = ["C", "o", "d", "e", "X"];
if(i < letters.length - 1) {
textPos.innerText = letters[i];
i ;
setTimeout(typewriter, 1000);
}
else {
let lastLetter = letters[letters.length - 1];
let span = document.createElement("span");
span.innerText = lastLetter;
span.style.color = "red";
textPos.appendChild(span);
}
}
typewriter();
<h1 id="js-headline"></h1>
CodePudding user response:
I hope this demonstration of an alternative typewriter function helps!
async function typewrite(word, ele) {
const letters = [...word];
const lastLetter = letters.pop();
for (letter of letters) {
ele.textContent = letter;
await new Promise(r => setTimeout(r, 500));
}
const aSpan = document.createElement("span");
aSpan.style.color = "red";
aSpan.textContent = lastLetter;
ele.appendChild(aSpan);
}
typewrite("Hello World!", document.querySelector("#output"));
<div id="output"></div>
CodePudding user response:
The positioning of array items starts from 0 so when you say i == letters.length
that property doesn't exist of array the last index on array is equal to letters.length - 1
you need to change the code to following:
let textPos = document.getElementById('js-headline');
let i = 0;
function typewriter() {
let letters = ['C', 'o', 'd', 'e', 'X'];
if (i < letters.length - 1) {
textPos.innerText = letters[i];
i ;
setTimeout(typewriter, 1000);
} else if (i == letters.length - 1) {
let lastLetter = letters[letters.length - 1];
lastLetter.style.color = 'red';
}
}
typewriter();
I hope it helped
Edit:
a little more about array indexing
for example in the following array the indexing is like below:
var array = ['a', 'b', 'c', 'd', 'e']
^ ^ ^ ^ ^
| | | | |
0 1 2 3 4
when you call array.length
it will return the number of elements in array but the first index starts from 0