Getting Started with jQuery Plugins

Wed, Mar 24, 2010 by Shawn

jQuery is an open source lightweight, cross-browser JavaScript library that is the most popular JavaScript library in use on the web today. Chances are, if you are a web developer or designer you have used or come across some plugins written in jQuery that have helped your web sites take advantage of JavaScript interaction with HTML with very minimal development.

As a developer learning how to develop your own jQuery plugin is extremely helpful as one can create any plugins they require for their site and in the spirit of open source, release them to the public.

Any web page that uses jQuery will have a ready event:
$(document).ready(function(){
    // Your code here
});

For this tutorial lets build a plugin that converts text on a page to a different color. A really simple plugin I know, but our primary goal is to learn about developing a plugin and not so much some awesome feature. You can create that later and thank me for getting you started. let's name our plugin colorChange.

Inside this ready event let's invoke your plugin:
$(document).ready(function(){
    $(selector).colorChange();
});

This code obviously will not work as we have not created a selector nor have we extended the plugin.

Now that you have the basics of how your plugin will be called, let's create the actual plugin. Create a new file and let's extend jQuery to add your colorChange function.

(function($){
    $.fn.colorChange = function() {
        return this.each(function() {
            $(this).css({'color':'#FF0000'});
        });
    };
})(jQuery);

Now with this code each selector that we pass to the plugin will get changed with the jQuery CSS method and change the text to the color red.

What if we wanted to pass the colors that we wanted to change the text to? We can do so by passing an option to the plugin at instantiation. Let's set up our plugin code to be able to take these parameters.

(function($){
    $.fn.colorChange = function(options) {
        return this.each(function() {
            if ( options.color ) {
                $(this).css({'color':options.color});
            }
            else {
                console.log('No color selected');
            }
        });
    };
})(jQuery);

As you can see in the above code, we have a condition to check if the option parameter returns true for a color. If not I've decided to degrade the program safely and provide a console error message and not break the overall functionality of the program. Of course when you develop your plugins, you are free to degrade a program how you wish.

you can also see that instead of hard coding a color hex value we are loading the options parameters color value. To send this color value to the plugin through the plugins initial instantiation you would do the following.

$(document).ready(function(){
    $(selector).colorChange({
        'color': '#FF0000'
    });
});

there you have it, your first basic jQuery plugin.

One thing that I'd like to add that is really cool about this plugin is that it is scalable with other jQuery methods. For example, you could have this plugin interact with a jQuery click event.

$(document).ready(function(){
    $(selector).click(function() {
        $(this).colorChange({
            'color': '#FF0000'
        });
    });
});

Check it out, play around and make a bigger and better plugin. Next time I'll go more in depth with adding some default options that can be extended inside the plugin as well as some other nifty tricks with jQuery plugins and some JavaScript OOP.

mthl posted on March 27, 2010 1:27 am

jQuery plugins should go in their own .js files and be called from tags in the header. For Drupal, that means adding a script item to your theme's .info file.

After that, you can call your plugin from any place in the page, either another .js file, or embedded in a block, or in a node.

Thomas Muirhead posted on March 26, 2010 7:30 am

Hi there,

I'm really excited about this post as learning jquery basics has been something I've been wanting to do for ages. It looks fairly straight forward, but would it be possible for you to give an example of how you would actually use the code - say on a drupal site.

You create the jquery file, but where do you put it?

You create the ready event, but again where do you put it? In the page.tpl.php or could you put it in a block snippet?

Your click function above...where are you defining what you are clicking? Are you wrapping an link in the jquery code?

Sorry if these questions seem silly - just trying to get my head around how to take the abstract theory above and put it on a page.

Thanks so much for the post

Thomas

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <h2>
  • Lines and paragraphs break automatically.

More information about formatting options