How should this code be improved? For instance:
- How could it be shorter, clearer, deal with memory better, use a plugin/library, better prepared for web input?
- I can break up and clarify the regex or jump calculation, but what is the simplest way?
- Why don't I see
setTimeout
cleared in if blocks more or default return values in||
inline? Am I dealing with the (potential) values properly? - Are there any other typewriter snippets or plugins accessible online that function with HTML5 rules and entities in a clearer way or is there a reason this is not often mentioned?
Description:
A typewriter effect outputs human readable characters one by one simulating actual typewriters. To ouput valid HTML5, entities, and text, sometimes we have to first output more than one character (like an entity or tag), and then output the rest of the tags in the block so that the A) outputted HTML snippet is not misread (according to its original state when output into the DOM), and B) so that the HTML in the snippet does not get read by the browser as part of any existing HTML on the page (in the DOM beneath the inserted snippet).
Usage:
customizeSnippet('homepage');
Input:
<div id="homepageSnippet"><p>A paragraph in an html5 snippet with no end tag & some text and entities.™<div><a href="http://www.w3.org/TR/html-markup/p.html#p">W3:paragraph</a></div>
Output, base state:
<div id="showSnippet"></div>
//2013-03-18
//Output HTML snippet - A char one by one, and a tag or an entity all at once
//Output all upcoming tags to preserve DOM integrity
//Recurse
var showSnippet = (function (target, snippet, snippetL, i, interval) {
var timeOut = 0,vis = '',tags = '',jump = [];
if (i < snippetL) {
if (snippet[i] === '<' || snippet[i] === '&') {
jump = snippet.substring(i).match(/^<[^>]+>|^&#?[A-Za-z0-9]+(?:;|\s|$|\v|\f|(<))/m);
i = i + (jump[0] || '1').length - 1 - (jump[1] || '').length;
}
vis = snippet.substring(0, i + 1) || '';
tags = ((snippet.substring(i + 1).match(/(<[^>]+>)/img) || []).join('')) || '';
$(target).html(vis + tags);
++i;
timeOut = window.setTimeout(function () {
showSnippet(target, snippet, snippetL, i, interval);
}, interval);
} else {
clearTimeout(timeOut);
}
});
//Get the widget html #pagenameSnippet and call showSnippet
//with the hardcoded div #showSnippet for output
var customizeSnippet = (function(page) {
var snippet = '', snippetL = 0;
snippet = $('div.'+page+'Snippet').html() || '';
snippetL = snippet.length;
if (snippetL > 0){
window.setTimeout(function(){
showSnippet("#showSnippet", snippet, snippetL, 0, 100);
}, 100);
}
});