Tuesday, September 22, 2009

Jumpstarting Your Next jQuery Plugin with an Online Tool

The following screencast focuses on how to quickly make a jQuery plugin. The intent is not to dig deep into the ins and outs of a jQuery Plugin’s wiring. If that is what you are looking for there are many other good tutorials out there for that such as…

This screencast’s focus is to build off of your current knowledge of how to build a jQuery Plugin (although it doesn’t have to be too deep), and allow you to quickly focus on the building your plugin, rather than worrying about how all the little pieces are wired together.

The tool we will be using is called Starter: jumptstart Your jQuery Plugins and you just provide the new jQuery Plugin name, optional namespace, parameters, options, etc… and then you are on your way focusing on the guts of your Plugin.

 

Update: This screencast has been posted on Nettuts+ for voting. If you like it, then please consider voting for the 3rd entry on the Nettuts+ blog post…

The plugin that we will be creating is an ImageTextOverlay that will allow you to provide a list of message and overlay them over a message. The message will fade in and out in succession and you will be able to change the properties of each message (such as it’s location, size, color, etc…). I was inspired to write this small plugin after hearing someone on Twitter wanting something similar to this.

Sometimes it is easiest if we look at how we want to use our Plugin before actually creating it. So, here is a simple page that is selecting an image and calling our imageTextOverlay plugin. You can see how there is a default top & left positions provided and then a list of messages. Each message only needs to have a text property provided, but you can also provide many other properties to override the default values.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="jquery.imagetextoverlay.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $('#ctlImage').imageTextOverlay({
                top: "10px",
                left: "10px",
                messages: [{
                        text: "Message 1"
                    }, {
                        text: "Message 2",
                        top: "50px",
                        left: "50px",
                        fontSize: "22px"
                    }, {
                        text: "Message 3",
                        top: "100px",
                        left: "100px",
                        color: "black",
                        fontSize: "48px",
                        backgroundColor: "#CCCCCC"
                    }, {
                        text: "Message 4",
                        top: "200px",
                        left: "200px",
                        letterSpacing: "-1px",
                        color: "red",
                        fontSize: "24px",
                        backgroundColor: "white"
                    }
                ]
            });
        });    
    </script>
</head>
<body>
    <img id="ctlImage" src="curtains.jpg" />
</body>
</html>

The next step is to starting entering our plugin Class Name and Default Options into the Starter: jumptstart Your jQuery Plugins online tool. Then we just click the Create button to prototype out our plugin! We can either copy/paste the results into our own file or there is even a Download button so you don’t have to copy/paste :)

StarterInput

Now we can focus on writing the core logic of our jQuery plugin and not have to worry about all the nuts and bolts of how a plugin should be structured. So, here is what I put together for the ImageTextOverlay plugin. I will highlight only the lines of code that I actually wrote… everything else was generated by the online tool!

(function($){
    
    $.ImageTextOverlay = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el; 
        
        // Add a reverse reference to the DOM object
        base.$el.data("ImageTextOverlay", base);
        
        base.init = function(){
            
            base.options = $.extend({},$.ImageTextOverlay.defaultOptions, options);
            
            // Put your initialization code here
            base.createAndUpdateImageText(base.$el, base.options);
        }
        
        // Sample Function, Uncomment to use
        // base.functionName = function(paramaters){
        //     
        // }

        base.createAndUpdateImageText = function($ctlImage, options) {
            var $ctlText = base.createImageText();
            base.updateImageText($ctlImage, $ctlText, options, function() {
               base.createAndUpdateImageText($ctlImage, options);
            });
        }        
        
        base.createImageText = function() {
            var $imageText = $('#ctlImageText');

            if ($imageText.length == 0) {
                $('<div id="ctlImageText" />')
                    .css({
                        position: "absolute"
                    })
                    .appendTo('body')
                    .hide();
                $imageText = $('#ctlImageText');
            }

            return $imageText;
        }    

        base.messageIndex = 0;
        base.updateImageText = function($ctlImage, $ctlText, options, onComplete) {
            var message = options.messages[base.messageIndex++ % options.messages.length];
            var messageOptions = $.extend({}, options, message);
            $ctlText.html(message.text).css({
                fontSize: messageOptions.fontSize
            });
            
            $ctlText.css({
                top: messageOptions.top,
                left: messageOptions.left,
                color: messageOptions.color,
                letterSpacing: messageOptions.letterSpacing,
                backgroundColor: messageOptions.backgroundColor,
            }).fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function() {
                onComplete();
            });
        }
        
        base.init();
    }
    
    $.ImageTextOverlay.defaultOptions = {
        fontSize: "24px",
        letterSpacing: "normal",
        color: "white",
        backgroundColor: "transparent"
    }

    $.fn.imageTextOverlay = function(options){
        return this.each(function(){
            (new $.ImageTextOverlay(this, options));
        });
    }

    // This function breaks the chain, but returns
    // the ImageTextOverlay if it has been attached to the object.
    $.fn.getImageTextOverlay = function(){
        return this.data("ImageTextOverlay");
    }
    
})(jQuery);

As I mentioned above, I only wrote the lines that are highlighted. The rest of the plugin was written by the Starter: jumptstart Your jQuery Plugins online tool!

If you are interested in other screencasts, I have made several others that you may be interested in as well…

No comments:

Post a Comment