Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show text letter by letter

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 using a brute-force approach (say, splitting the characters and print them one by one using jQuery.append()), I'm hoping there's some CSS3 (pseudo-elements?) or JQuery magic to do this more elegantly.

Extra points if the solution considers inner HTML content.

like image 736
hpique Avatar asked Sep 01 '11 00:09

hpique


People also ask

How do you show letters by text in CSS?

Steps() function in CSS It specifies whether the change in output percentage happens at the start or end of the interval. Using this function, we can control the text transition and show the letter one after another.


2 Answers

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);    }); 
like image 164
armen.shimoon Avatar answered Sep 23 '22 06:09

armen.shimoon


If a smooth reveal is reasonable then I think this should be pretty straightforward. Untested, but this is how I imagine it would work

html

<div id="text"><span>The intergalactic space agency</span></div> 

css

div#text { width: 0px; height: 2em; white-space: nowrap; overflow: hidden;  } 

jQuery

var spanWidth = $('#test span').width(); $('#text').animate( { width: spanWidth }, 1000 ); 

Okay, I couldn't resist and made a fiddle. One little code error that I fixed. Looks good to me though!

http://jsfiddle.net/mrtsherman/6qQrN/1/

like image 42
mrtsherman Avatar answered Sep 23 '22 06:09

mrtsherman