Typing Effect with HTML and Javascript

When searching for examples of a typing effect using HTML and Javascript, many sites say something like the following:

First an empty paragraph is added to the page.

<p id="message_para1"></p>

Then a recursive function is used that appends the text one character at a time to the paragraph, with a small delay each time using setTimeout.

let message = "Perfection is achieved, not when there is nothing more to add, 
but when there is nothing left to take away.";
    
const typeMessage1 = (message) => {
    let message_para1 = document.getElementById("message_para1");
    let i = 0;

    function addNextChar() {
        if (i < message.length) {
            message_para1.innerHTML += message.charAt(i);
            i++;
            setTimeout(addNextChar, 60);
        }
    }

    addNextChar();
}

Enable Javascript to see example.

While this does work, words will start appearing even when there is not enough space on the current line, and then drop down to the next line.

Method Two

With this alternate method, the entire text is already on the page, but every character is invisible. The visibility of each character is then restored one at a time.

Like before, start with an empty paragraph.

<p id="message_para2"></p>

Add an invisible class.

.invisible {
    visibility: hidden;
}

The text is then inserted into the paragraph.

For each character a new span is created, and the character is inserted into it. The span is given two class names, one to identify it later, in this case "messageChar", and the "invisible" class.

const createMessage = (message) => {
    let message_para2 = document.getElementById("message_para2");
    
    for (let i = 0; i < message.length; i++) {
        let span = document.createElement("span");
        span.innerText = message.charAt(i);
        span.className = "messageChar invisible";

        message_para2.insertBefore(span, message_para2.childNodes[i]);
    }
}

Enable Javascript to see example.

Now a recursive function is used to remove the "invisible" class from each span with a small delay using setTimeout.

const typeMessage2 = () => {
    let messageChars = document.querySelectorAll(".messageChar");
    let i = 0;

    function showNextChar() {
        if (i < messageChars.length) {
            messageChars[i].classList.toggle("invisible");
            i++;
            setTimeout(showNextChar, 60);
        }
    }

    showNextChar();
}

Enable Javascript to see example.

This site uses cookies to remember the currently selected theme.