I was facing the same problem. The difference with the above-mentioned code was that I was inserting an array of texts.
None of the above-mentioned solutions seemed to work, whether it was inserting \n or a <br />
element. The solution suggested here, was also not working. I guess what the problem was, is that typewriter effect inserts the aforementioned solutions (inserting \n or a <br />
) char by char, causing HTML not to recognize the break statements.
What I did was the following, I coded that every time the txt element, contained a "*", the typewriter function would at once insert a <br/>
element in the HTML. This worked fine.
//e.g. of txt message:
txt = `Please type one of the following commands to get to know me: **about *projects. **To contact me, insert contact in the command line.`
//e.g. of inserting the individual letters
function insertLetter(i){
return new Promise((resolve, reject) => {
if(txt.charAt(i)==='*'){
document.getElementById(id).innerHTML += `<br/>`;
console.log("we were at the line break section")
resolve(i)
}else{
document.getElementById(id).innerHTML += txt.charAt(i);
resolve(i);
}
})
}
This gives the following:
"Please type one of the following commands to get to know me:
about
projects.
To contact me, insert contact in the command line."
PS: contrary to the code that was present on W3 schools, I work with various .then statements, making sure that each letter is typed out before moving to the next letter. The same goes for multiple txt messages that I display which are stored in a txt array. I noticed that using the example of W3 can cause the letters to be mixed, as well as moving on to the next txt statements in the array before finishing the first typewriter effect.