Friday, November 11, 2011

Tutorial: Creating a jQuery plugin

Tutorial: Creating a jQuery plugin
Learn how to create a jQuery plugin from scratch – the basics, options, compatibility and examples.

The Basics

A plugin is written as a method or function.

Creating a jQuery Function

Syntax
The function has to return this.each(..) to maintain chainability – so that the function can be used with a single or several jQuery objects.
jQuery.fn.myFunction = function(){
    return this.each(function(){
        // element-specific code here
    });
};
Example
jQuery.fn.makeTextRed = function(){
    return this.each(function(){
        $(this).css('color', 'red');
    });
};
 
// Example usage
$('#my-div').makeTextRed(); // make text in "my-div" red
$('p').makeTextRed(); // make all paragraphs red

Creating a jQuery Method

Syntax
jQuery.myMethod = function(){
    // code here
};
Example
jQuery.sayHelloWorld = function(){
    alert('Hello World');
};
 
// Example usage
$.sayHelloWorld(); // alerts "Hello World"

Options

Make your plugin as flexible and user friendly as possible using options. The $.extend() method takes two or more objects as arguments and merges the contens of them into the first object.
Example
A function that set text color (red by default).
jQuery.fn.makeTextColored = function(settings){
    var config = {
        'color': 'red'
    };
    if (settings){$.extend(config, settings);}
 
    return this.each(function(){
        $(this).css('color', config.color);
    });
};
We can now choose use this function passing the settings parameter or not.
$('#my-div').makeTextColored(); // make text red (default)
$('#my-div').makeTextColored('blue'); // make text blue

Compatibility

As the $ variable might be used by other plugins, use a alias technique to make your plugin forward-compatible.
(function($){
$.fn.myFunction = function() {
    return this.each(function() {
        // element-specific code here
    });
 };
})(jQuery);
We pass jQuery to the function and can now use whatever alias for jQuery we like. So instead of $ you could also use any other valid JavaScript variable name.

The jQuery Plugin Checklist

This is a list of important points to remember when developing a jQuery plugin (from jQuery.com).
  • Name your file jquery.[insert name of plugin].js, eg. jquery.debug.js
  • All new methods are attached to the jQuery.fn object, all functions to the jQuery object.
  • inside methods, this is a reference to the current jQuery object.
  • Any methods or functions you attach must have a semicolon (;) at the end – otherwise the code will break when compressed.
  • Your method must return the jQuery object, unless explicity noted otherwise.
  • Use this.each to iterate over the current set of matched elements.
  • Always attach the plugin to jQuery instead of $, so users can use a custom alias via noConflict().

jQuery Plugin Templates

These are two good code templates to start from when developing a jQuery plugin.

Function Template

(function($){
    $.fn.myPlugin = function(settings){
        var config = {
            'foo': 'bar'
        };
        if (settings){$.extend(config, settings);}
 
        return this.each(function(){
            // element-specific code here
        });
    };
})(jQuery);

Method Template

(function($){
    $.myPlugin = function(settings){
        var config = {
            'foo': 'bar'
        };
        if (settings){$.extend(config, settings);}
 
        // code here
 
        return this;
    };
})(jQuery);

Example: jQuery Slideshow Plugin

I have chosen to use very simple examples so far in order for you to get started. The following example is a bit more complex and might help to get your inspiration going.
It uses the function setInterval() in combination with the jQuery effects fadeOut() and fadeIn() to cycle any number of images within a HTML-element.

The Setup

HTML
<div id="slideshow">
    <img src="img/sample-image-1.png" alt="" />
    <img src="img/sample-image-2.png" alt="" />
    <img src="img/sample-image-3.png" alt="" />
    <img src="img/sample-image-4.png" alt="" />
</div>
CSS
#slideshow img {
    display: none;
    position: absolute;
}
JavaScript
(function($){
    $.simpleSlideShow = function(selector, settings){
        // settings
        var config = {
            'delay': 2000,
            'fadeSpeed': 500
        };
        if ( settings ){$.extend(config, settings);}
 
        // variables
        var obj = $(selector);
        var img = obj.children('img');
        var count = img.length;
        var i = 0;
 
        // show first image
        img.eq(0).show();
 
        // run slideshow
        setInterval(function(){
            img.eq(i).fadeOut(config.fadeSpeed);
            i = ( i+1 == count ) ? 0 : i+1;
            img.eq(i).fadeIn(config.fadeSpeed);
        }, config.delay);
 
        return this;
    };
})(jQuery);

Usage

To enable slideshow on the #slideshow div, we simply call it using the following JavaScript code:
<script type="text/javascript">
$.simpleSlideShow('#slideshow');
</script>
Because we allow settings to change the behaviour of the slideshow, we could make it wait 5 seconds between images and set the “fade” duration to 200 ms using:
<script type="text/javascript">
$.simpleSlideShow('#slideshow', {'delay':5000, 'fadeSpeed': 200});
</script>
View Example Download Example
 

No comments:

Post a Comment