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.