What is the most elegant way of showing an html text letter by letter (like videogame captions) using CSS and JavaScript?
While I\'m sure that his can be solved usin
HTML
<div id="msg"/>
Javascript
var showText = function (target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
}
Call with:
$(function () {
showText("#msg", "Hello, World!", 0, 500);
});
You really should just append
, or show/hide.
However, if for some odd reason you don't want to alter your text, you can use this overly-complicated-for-no-good-reason piece of code:
HTML:
<p>I'm moving slowly...<span class="cover"></span></p>
CSS:
p {
font-family: monospace;
float: left;
padding: 0;
position: relative;
}
.cover {
height: 100%;
width: 100%;
background: #fff;
position: absolute;
top: 0;
right: 0;
}
jQuery:
var $p = $('p'),
$cover = $('.cover'),
width = $p.width(),
decrement = width / $p.text().length;
function addChar()
{
$cover.css('width', '-=' + decrement);
if ( parseInt( $cover.css('width') ) < width )
{
setTimeout(addChar, 300);
}
}
addChar();
And finally, here's the fiddle: http://jsfiddle.net/dDGVH/236/
But, seriously, don't use this...
I was trying to solve the same problem and I came up with this solution that seems to work.
HTML
<div id='target'></div>
jQuery
$(function() {
var message = 'Hello world';
var index = 0;
function displayLetter() {
if (index < message.length) {
$('#target').append(message[index++]);
}
else{
clearInterval(repeat);
}
}
var repeat = setInterval(displayLetter, 100);
});
100% vanilla javascript, strict mode, unobtrusive html,
function printLetterByLetter(destination, message, speed){
var i = 0;
var interval = setInterval(function(){
document.getElementById(destination).innerHTML += message.charAt(i);
i++;
if (i > message.length){
clearInterval(interval);
}
}, speed);
}
printLetterByLetter("someElement", "Hello world, bonjour le monde.", 100);
This is based on armen.shimoon's:
var showText = function (target, message, index, interval) {
if (index <= message.length && $(target).is(':visible')) {
$(target).html(message.substr(0, index++));
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
}
message[index++] wasn't working in my jquery webpage - I had to change it to substr. Also my original text uses HTML and the text that is typed uses HTML formatting (br, b, etc). I've also got the function stopping if the target has been hidden.
There are a couple libraries for this now. There are TypeItJs and TypedJS both of them allow for html to be in the thing that you are typing out as well as numerous other methods that assist in animating Typewriter effects.