jQuery Plugin Tutorial Part IV - The Options

As discussed in part one, our target is to create a voter that will allow visitors to vote on something. So we need at least two parameters passed to this function and they are starting value and the maximum value. Let us see how we can pass these variables to our plugin.
    $.fn.voter = function(options){
        //The following are the default values
        var settings = {
         //if options are passed
        //to the plugin
            //the following line merges the
            //variable 'settings' and 'options'
            //overwriting the values in 'settings'
            $.extend( settings, options );                
        return this.each(function(){
           //our functionality here
You will be able to understand the above code by taking a look at the comments. Take a look at this link to learn more about the $.extend() function.
Now when we call the plugin, we can set the options like shown below.
This will set the "start" value to '10'. The end value will still be the default value which is 100.

No comments:

Post a Comment