I have written a jQuery plugin (my first for a long time) that simply cycles through strings of text in a data attribute and uses setInterval
to type it out - it's a common effect you've probably seen hundreds of times.
I'm looking for a code review of the JavaScript/jQuery portion of the code mainly because a lot of the literature on building a jQuery plugin is quite old and I want to be sure I'm doing things the "modern" way.
$(document).ready(function() {
$().typeText();
});
(function($) {
$.fn.typeText = function(options) {
var settings = $.extend({
loopSpeed: 5000,
typeSpeed: 100,
selector: '.words'
}, options);
var typeIntervals = [];
load();
function load() {
$(settings.selector).each(function() {
var wordsArray = $(this).data('words').split(',');
var length = wordsArray.length - 1;
var index = 0;
var thisWordGroup = $(this);;
if (typeof $(this).data('index') == 'undefined') {
$(thisWordGroup).data('index', 0);
}
$(this).html(wordsArray[0]);
});
setIntervals();
}
function setIntervals() {
setInterval(function() {
clearTypeIntervals();
$(settings.selector).each(function() {
var thisWordGroup = $(this);
var wordsArray = thisWordGroup.data('words').split(',');
var length = wordsArray.length - 1;
var index = thisWordGroup.data('index');
index++;
if (index > length) {
index = 0;
}
thisWordGroup.data('index', index);
type(thisWordGroup, wordsArray[index]);
});
}, settings.loopSpeed);
}
function type($selector, word) {
$selector.html('');
var index = 0;
var splitWord = word.split('');
var splitWordLength = splitWord.length - 1;
var intervalName = 'typeWordInterval' + Math.ceil(Math.random() * 99999);
typeIntervals[intervalName] = setInterval(function() {
var currentText = $selector.html();
$selector.html(currentText + splitWord[index]);
if (index < splitWordLength) {
index++
} else {
clearInterval(typeIntervals[intervalName])
}
}, settings.typeSpeed);
}
function clearTypeIntervals() {
for (var element in typeIntervals) {
clearInterval(typeIntervals[element]);
}
}
}
}(jQuery));