I try to create a typeWriter effect using Javascript. It done perfectly, but it cannot type ‘<‘ character. I don’t know how to fix it
My code is:
let other = document.getElementById('other');
let txt = "Hello World <br> this typing effect.";
let i = 0;
function typeWriter() {
if (i < txt.length) {
other.innerHTML += txt.charAt(i); i++;
setTimeout(typeWriter, 10);
window.scrollTo(0, document.body.scrollHeight);
}
}
typeWriter();
<h1 id='other'></h1>
I hope the result like:
Hello World
this typing effect.
Actual result I get:
Hello World <br> this typing effect.
Please give me some clue. Thanks in advance
2
Answers
Perhaps you can handle each instance of
<br>
by:<sometag>
,<sometag>
toother.innerHTML
,You can also extend this to handle any HTML tag by checking for the pattern of
<foo>...</foo>
if you want to try tags including anchor and list elementsYou just need to know two things,
How
white-space
are handled in html?By nature it will collapse all the extra spaces and line into linear format.
You can break it using
white-space
css property. MDNEscape characters (escape sequence)
A character escape represents a character that may not be able to be conveniently represented in its literal form.
Here
n
denotes a new line. MDN