Jun 5, 2012
Type out Text
Posted in "development"
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
Example
<iframe style="width:100%; height: 100px" src="http://jsfiddle.net/darcyclarke/xC7gT/56/embedded/result" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
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