HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

jQuery plugin to cycle through text and "typewrite" it out

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cycletypewritetextpluginjquerythroughandout

Problem

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.

CodePen

```
$(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[intervalNa

Solution

The API design is rather weird. You expect your plugin to be called like

$().typeText({ selector: '.words' })


But a design like this would be much more natural for jQuery:

$('.words').typeText()

Code Snippets

$().typeText({ selector: '.words' })
$('.words').typeText()

Context

StackExchange Code Review Q#104591, answer score: 7

Revisions (0)

No revisions yet.