I’m just trying to create a function with a parameter, but it says that the parameter is undefined.
It’ll be clearer with the example:
const txt = ["Some text here"];
let textPosition = 0;
const speed = 25;
function typeWriter(element) {
document.getElementById("paragraph1").innerHTML = element[0].substring(0, textPosition);
if(textPosition++ != element[0].length) {
setTimeout(typeWriter, speed);
} else {
CallButton.classList.toggle("hidden");
}
};
typeWriter(txt);
<span id="paragraph1"></span>
So I’m clearly doing something wrong here, but I do not know what and why.
The code should simply insert in paragraph1 the string in the txt array in a typewriter style. It is working when I replace element with txt.
But since I need to call the same function multiple times for different text, so different arrays with different text in each, I need to pass a parameter, so that I can reuse the function.
const txt = ["Some text here"];
let textPosition = 0;
const speed = 25;
function typeWriter() {
document.getElementById("paragraph1").innerHTML = txt[0].substring(0, textPosition);
if(textPosition++ != txt[0].length) {
setTimeout(typeWriter, speed);
}
};
typeWriter();
<span id="paragraph1"></span>
setTimeout(typeWriter, speed);there won't be any arguments passed, when called here.setTimeout?textPosition++ === txt[0].length.