0

Typewriter-Effect for HTML with JavaScript

I saw this post about "typewriter" effect in Javascript, and thought this was a very nice effect. I am now working on a kind of "terminal" in the browser, but I stumbled upon the problem where the text just gets replaced, and not added to a new line if you call the function multiple times.

Here's an example.

function writeText(target, string, speed) {

  var i = 0;
  var isTag, text;

  (function type() {

    text = string.slice(0, ++i);
    if (text === string) return;

    target.html(text);

    var char = text.slice(-1);
    if (char === '<') isTag = true;
    if (char === '>') isTag = false;
    if (isTag) return type();

    setTimeout(type, speed);

  }());

}

var output = $('#output');
writeText(output, 'This is a test string.', 20);
writeText(output, 'This is a string that replaces the first one.', 20);
<div id="output"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Is there an easy way to improve the script to create a new line, each time the function is called? I've tried using .append() instad of .html() but that didn't work either. The code snippet I am using is posted by Tachun Lin in the other post.

Thanks in advance.

Community
  • 1
  • 1
Kaizokupuffball
  • 2,703
  • 8
  • 38
  • 58
  • Do you want to print the both lines in same time? or display the second just after the first done? – Zakaria Acharki Sep 24 '16 at 14:15
  • I want to print the second line after the first. Just like a regular console. I am adding input later, so that when the user inputs a command, the response is added on a new line, below the top one. – Kaizokupuffball Sep 24 '16 at 14:17

0 Answers0