Skip to content

Instantly share code, notes, and snippets.

@jacoborus
Created November 8, 2012 00:16
Show Gist options
  • Save jacoborus/4035577 to your computer and use it in GitHub Desktop.
Save jacoborus/4035577 to your computer and use it in GitHub Desktop.
Simple jQuery/Zepto plugin for typing character by character texts
/**
* jQuery.letterByLetter
* Version 0.3.0
*
* Simple jQuery/Zepto plugin for typing character by character texts
* Standard call:
$('.myDivs').LetterByLetter({
'speed' : 150
});
* Where myDivs is the class of the items you want to type in order of appearance.
*
* Available options with defaults
'speed' : 150, // Interval between characters in milliseconds
'callback' : null, // callback function
'pause' : 300 // Delay between texts in milliseconds
* github.com/jacoborus
* MIT license
*
*/
(function($) {
'use strict';
$.fn.LetterByLetter = function(options) {
var nlayers, alllayers, pos, settings, typing;
settings = $.extend({
speed: 150, // Interval between charactersin milliseconds
callback : null, // Callback function
pause : 1000 // Delay between texts in milliseconds
}, options);
alllayers = this;
nlayers = this.length;
pos = 0;
// hide target layers
$(this).each(function(index) {
return $(this).css("display", "none");
});
// typing function writes text character by character
typing = function(capa) {
var count, step, clock, out, textlong, texto;
// get the target text
texto = $(capa).html();
// get the text long
textlong = texto.length;
// out text
out = "";
// character counter
count = 0;
// write next character
step = function() {
// add new character to out and count
out = out + texto.charAt(count++);
// write type
$(capa).html(out);
// display the layer if first character
if (count === 1) $(capa).css("display", "");
// if last character and type next layer
if (count === textlong) {
// stop clock
window.clearInterval(clock);
// if not last layer
if (pos < nlayers) {
// run next text with delay
return setTimeout( function(){
typing($(alllayers)[pos++]);
}, settings.pause);
} else {
// run callback
if (settings.callback !== null) {
return settings.callback();
}
}
}
};
// avoid repeating first layer
if (pos === 0) pos++;
// typing a character every settings.speed milliseconds
return (clock = setInterval(step, settings.speed));
};
// start typing first layer
typing(this[0]);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment