I’ve decided to start posting semi-daily code snippets. I’ve got a number of posts that touch in this very area and I need to get them published (so I’m hoping this will help spur them on into the light of day).
After watching some of the E3 action today, I noticed a lot of the FPS (First Person Shooter) games seem to use the same animation technique to display text on the user’s HUD (Heads Up Display). It’s similar to a ghost typing on your computer and isn’t anything new. That said, I’ve never written anything for it before so I decided to whip up a quick snippet.
The below jQuery plugin, .typeOut(), simply grabs the text of the selected element, removes it and then slowly re-adds it back into the DOM.
Optional Settings
preserve(true/falseDefault:false)
Maintains HTML within the elementmarker(stringDefault:'_')
Sets the marker that is placed before the typed textdelay(number in msDefault:90
Sets the delay between display of characters
Example
The Code
(function($){
$.fn.typeOut = function( options ){
return this.each(function(){
var el = $(this),
tags = /(<\/?\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>)/gim,
entities = /(?[a-z0-9]+;)/gim,
settings = $.extend( {
delay : 90,
preserve : false,
marker : '_'
}, options),
html = (function(){
var temp = el.html().trim().split(tags),
html = [],
x = 0;
temp.map(function(v,i){
if(v.indexOf('<') < 0){
temp[i] = v.split(entities);
temp[i].map(function(v,i){
if(v.indexOf('&') < 0){
v = v.split('');
v.map(function(v){
if(v != '')
html.push(v);
});
} else {
html.push(v);
}
});
} else {
if(temp[i] != '')
html.push(temp[i]);
}
});
return html;
})(),
step = function(num){
el.html(el.html().slice(0,-1)+html[num]+settings.marker);
num = num + 1;
if(num < html.length){
setTimeout(function(){
step(num);
}, settings.delay);
} else {
el.html(el.html().slice(0,-1));
}
};
settings.marker = (settings.marker != '') ? settings.marker : ' ';
html = (settings.preserve) ? html : el.text().split('');
el.html('');
if(html.length >= 1)
step(0);
});
};
})(jQuery);
Github: jQuery tyepOut Plugin
Suggestions, problems, feedback?
Check Out the Repo

1 Comments
I would suggest checking out this little project.
http://onehackoranother.com/projects/jquery/jquery-grab-bag/text-effects.html
Leave a Reply: