Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Developing a jQuery Plugin

4.67/5 (2 votes)
19 Jun 2014MIT 11.7K  
Basic framework for a jQuery plugin

Introduction

So I have written several jQuery plugins and over the years, I have developed a basic foundation for starting a new plugin.

Background

This is a piece of JavaScript code that I have gathered and developed over the years. When I first started to write plugins, a lot of it just confused me. Hopefully, if you are new and/or interested in jQuery and wanting to write your own plugins, this will help.

Using the Code

I have tried to comment the code as reminders for myself when developing a new plugin but also a guide for any other developers starting from scratch.

So I am going to let the following code just speak for itself:

JavaScript
(function($) {
    // using $.fn.extend allows us to expand on jquery
    $.fn.extend({pluginName:function(options){
        // save a link to your instance
        var plugin = this;
        
        var defaultOptions = {
            // add what you know are default values for your options
        };
        
        // connect your default values to what the user has added
        // I connect everything into the current instance so that it 
        // can be referenced later if needed.
        if (options)
            plugin.Settings = $.extend(defaultOptions, options);
        else
            plugin.Settings = defaultOptions;
            
        // private functions
        function functionName(values){
            // code here
        }
        
        // public functions
        plugin.functionName = function(values){
            // code here
        }
        
        // implement get/set for your object properties
        var variableName;
        plugin.variableName = function(v){
            // validate data sent in
            if(undefined !== v){
                variableName = v;
            }
            
            return variableName;
        }
    
        return this.each(function(){
            // initialization code goes here
        });
    }});
})(jQuery);

Happy coding!!!

History

  • 19-Jun-2014 - Initial release

License

This article, along with any associated source code and files, is licensed under The MIT License