简体   繁体   中英

How to print multi-line text letter by letter from JavaScript?

I want to print my text letter by letter using JavaScript. I tried the following answer https://stackoverflow.com/a/7265613/7920589 which is in jQuery by converting it into plain javascript.

     let showText = function (target, message, index, interval) {
            if (index < message.length) {
                document.querySelector(target).innerText += message[index++];

                setTimeout(function () { showText(target, message, index, interval); }, interval);
            }
            }
     showText("#msg", "Hello this line is printing letter by letter\n hello this line too is printing letter by letter,", 0, 200);

I tried this code but though it prints the message letter by letter, it completely ignores the spaces in the message.

OUTPUT:

Hellothislineisprintingletterbyletter
hellothislinetooisprintingletterbyletter,

I tried replacing innerText with innerHTML and textContent but then the new line escape character \\n does not work and instead prints a simple space instead on going to a new line.

OUTPUT:

Hello this line is printing letter by letter hello this line too is printing letter by letter,

Please help me with this.

You could use a <code> tag in combination with textContent and white-space: pre-wrap :

 let showText = function(target, message, index, interval) { if (index < message.length) { document.querySelector(target).textContent += message[index++]; setTimeout(function() { showText(target, message, index, interval); }, interval); } } showText("#msg", "Hello this line is printing letter by letter\\n hello this line too is printing letter by letter,", 0, 20);
 code { white-space: pre-wrap }
 <code id="msg"></code>

An alternative to what CertainPerformance proposed is to slice the text.

 let showText = function(target, message, index, interval) { if (index < message.length) { document.querySelector(target).textContent = message.slice(0, index); setTimeout(function() { showText(target, message, index + 1, interval); }, interval); } } showText("#msg", "Hello this line is printing letter by letter\\n hello this line too is printing letter by letter,", 0, 20);
 div { white-space: pre-wrap; }
 <div id="msg"></div>

maybe you should try this kind of loop to print letter by letter

<input type="text" id="input1">
<button onclick="his()">click</button>

and the js

function his() {
    let input = document.getElementById("input1").value
    for (let index of input) {
        console.log(index)
    }
}

i just discover this type of loop and its kinda has short syntax. maybe this could help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM