skip to Main Content

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


  1. Perhaps you can handle each instance of <br> by:

    1. applying the typewriter until encountering tag: <sometag>,
    2. directly adding <sometag> to other.innerHTML,
    3. continue applying your effect to the rest of the string.
    let other = document.getElementById('other');
    let txt = "Hello World <br> this typing effect.<br>break again?!";
    let i = 0;
    
    function typeWriter() {
      if (i < txt.length) {
        if (txt.substring(i, i + 4) === '<br>') {
          other.innerHTML += '<br>';
          i += 4;
        } else {
          other.innerHTML += txt.charAt(i);
          i++;
        }
        setTimeout(typeWriter, 10);
        window.scrollTo(0, document.body.scrollHeight);
      }
    }
    
    typeWriter();
    <h1 id='other'></h1>

    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 elements

    Login or Signup to reply.
  2. You just need to know two things,

    1. 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. MDN

    2. Escape 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

    let other = document.getElementById('other');
    let txt = `Hello World nthis 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();
    #other{
      white-space: pre-line; /* magic is here */
    }
    <h1 id='other'></h1>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search