jtyper: The Making of a jQuery Plugin

I have a website project that needs an intro/tutorial page. This will be the first impression one will get when visiting the site, so the extra weight of Flash or a movie seems a bit overkill. The site already utilizes the jQuery library therefore I’m going to create a simple, lightweight animation using javascript. If it’s worth building once, it’s worth repeating, right? And if I’m going to repeat it, why not take the extra step and keep it DRY by creating a customizable plugin? Here is the making of the jQuery plugin: jtyper.

Step 1: Decide What the Plugin Does

I want to keep it super simple: Display a few descriptive and directional statements one at a time as if they are being typed on the screen in real time. At the end of each typed line I will trigger a little animation.

Step 2: Figure Out What Is Configurable

The most obvious configurable item is the message. The simplest way for me to pass this will be with an array of individual lines of text.

I want to trigger an animation at the end of each typed line, so I’ll use an optional callback function that is triggered at the end of each line of text. I will have to pass the current position in the array so I can use a switch/case to apply different animations based on the line of text just rendered.

Eventually I’ll want to add a few other configurable items like like a randomize & repeat flag and a typing speed option, but for the sake of this demo I’ll keep it bare bones.

Step 3: Build Functionality as a Javascript Object

I’m gonna start with a stand alone javascript function or object. If I can get a stand alone object to perform to the general specs I’ve laid out above, it won’t be too difficult to convert into a plugin later.

The HTML Container
I am going to render the typing in to a DIV with the id "mydiv" : <div id="mydiv"></div>

The Javascript Object

<script type="text/javascript">
var jTyper = function(element) {
    var target = element;
    var phrase = 0;
    var letter = 0;
    var settings = {
        callback:   null,
        messages:   [
            'hickory dickory dock',
            'the mouse ran up the clock',
            'the clock struck one',
            'the mouse did run',
            'hickory dickory dock'
        ]
    };
        
    var startPhrase = function() {
            
        if (typeof(settings.messages[phrase]) == 'undefined') {
            return;
        }
        
        target.empty();
        letter = 0;
        startLetter();
    };
        
    var startLetter = function() {
        if (typeof(settings.messages[phrase][letter]) == 'undefined') {
            if (typeof(settings.callback) == 'function') {
                settings.callback(phrase);
            }

            phrase = phrase + 1;
            setTimeout(function(){startPhrase()}, 3000);
            return;
        }

        target.append(settings.messages[phrase][letter]);
        letter = letter + 1;
        setTimeout(function(){startLetter()}, 250);
    };

    startPhrase();
};
</script>

It is important to define scope specific variables and methods within the object to allow for functioning, independent instances.

Currently the only configurable variable is the jQuery element. Otherwise it is a one trick pony in that it will only type out the words of a nursery rhyme. Creating an instance will call the startPhrase() method and start rendering the typing within the provided target jQuery element $(‘#mydiv’). Each phrase in the array settings.messages will be typed line-by-line, letter-by-letter.

<script type="text/javascript">
$(document).ready(function(){
    var myjtyper = new jTyper($('#mydiv'));
});
</script>

Step 4: Convert to Plugin and Add Options

Now that I’ve got the hard part over, converting the javascript object into a jQuery plugin is simple. If you are unfamiliar with the jQuery plugin architecture and authoring, take a look at http://docs.jquery.com/Plugins/Authoring.

I will need to pass my options to the object (line 2) to redefine the defaults I set up in settings. In lines 6 and 15, see how jQuery’s $.extend will accept new values for messages and callback.

(function($){
    var jTyper = function( element, options ) {
        var target = $(element);
        var phrase = 0;
        var letter = 0;
        var settings = $.extend({
            callback:     null,
            messages:   [
                'hickory dickory dock',
                'the mouse ran up the clock',
                'the clock struck one',
                'the mouse did run',
                'hickory dickory dock'
            ]
        }, options || {});
        
...        

        startPhrase();
    };
 
    $.fn.jtyper = function( options ) {
       return this.each(function() {
            (new jTyper(this, options));
        });
    };
})(jQuery); 

By putting the object inside the plugin namespace and passing it element and options, I can loop through each instance of jtyper and pass the respective params to a independent instance of my jTyper object.

Step 5: Putting It All Together

I have created a jQuery plugin named jtyper! Now I can simply instantiate my object on any element with the following syntax:

$('#mydiv').jtyper({
    messages: [
        'hello',
        'hi there',
        'custom message'
    ],
    callback: function(el) {
        alert('Just rendered phrase # ' + el);
    }
});

It uses my custom message. I’ve also added a custom callback function. I can set up a single method with different cases for each element of messages represented with el — when the line ‘hello’ is display, 0 is passed to my callback function; after ‘hi there’, 1; and so on.

See examples, download the current version, and read documentation for jtyper at bitbucket.org/viction/jtyper. Let me know if you want to contribute, have any feature requests or find any bugs.

Did you like this? Share it:

About Doli Stepniewski

Application developer, designer, musician and artist -- CTO at Just A Pinch Recipe Club, LLC -- Former partner and chief architect at echo (echomusic, LLC) -- Creator of the echotools(tm) fan management, CRM, CMS and eCom platform.
This entry was posted in Coding, Design and tagged , , , . Bookmark the permalink.