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.
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.
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); });
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With