Sheel
Sheel

Reputation: 1030

How to create function for custom jQuery plugin

I am creating one simple custom jQuery plugin using jquery.boilerplate.js. Now I want to create one function that will call like,

var div1 = $("#div1").changeBackgroundColor({
  color: $('#colorCode').val().trim()
});
div1.getColor();

How to defined that getColor() method in jquery plugin.

Custom Plugin:

;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor", defaults = {
    color : "black"
};

function Plugin(element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
}

$.extend(Plugin.prototype, {
    init : function() {
        console.log("Hello");
    }
});

$.fn[pluginName] = function(options) {
    this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this,
                    options));
            }
        console.log(options);
        if(options===undefined){
            $(this).css("background-color", defaults.color);
        } else{ 
            $(this).css("background-color", options.color);
        }
    });
    return this;
};

})(jQuery, window, document);

Thank You....:)

Upvotes: 0

Views: 309

Answers (3)

Shubham Kumar
Shubham Kumar

Reputation: 1229

Create your Plugin like this:

$.fn.highlight = function(){
  this.css("background","yellow").css("color","black");
  return this;
}

$(".highlight").highlight().fadeIn();
In the above example i had created a simple jQuery plugin which will highlight a element.I think you should check this http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You kinda missed the whole point of plugins and OOP.

  1. $.fn[pluginName] - should play infrastructure role and delegate actual work to the Plugin instance.
  2. Plugin instance should perform actual work with element.
  3. If you want to call methods on Plugin instances you can make $.fn[pluginName] to handle special cases when options is a string. $(selector).changeBackgroundColor('methodToBeCalled' /*rest arguments*/)

Demo.

;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor", 
    defaults = {
        color : "black"
    },
    //methods to be called via $().changeBackgroundColor(name)
    publicMethods = { 
        getColor: function() {
            return this.settings.color;        
        },
        setColor: function(color) {
            this.settings.color = color;
            this.element.css('background-color', color);            
        }
    },
    privateMethods = { //internal methods
        init : function() {
            console.log('init');
            this.setColor(this.getColor());            
        }
};

function Plugin(element, options) {
    this.element = $(element);
    this.settings = $.extend({}, defaults, options);

    this.init();
}

//copy private and public methods
$.extend(Plugin.prototype, privateMethods, publicMethods); 

$.fn[pluginName] = function(options) {
    var out = [],
        args = [].slice.call(arguments, 1);
    this.each(function() {
        var plugin = $.data(this, pluginName), 
            method;

        if (!plugin) { //create new plugin  
            plugin = new Plugin(this, options)                  
            return $.data(this, pluginName, plugin);            
        }
        //handle method calls
        if(typeof options === 'string' && publicMethods[options]) { 
            out.push(plugin[options].apply(plugin, args));
        }        
    });
    return out.length ? (out.length === 1 ? out[0] : out) : this;
};

})(jQuery, window, document);

Usage

$('#a').changeBackgroundColor();
$('#b').changeBackgroundColor({color: 'navy'});
$('#c').changeBackgroundColor({color: 'green'});
console.log($('#b').changeBackgroundColor('getColor'));
console.log($('#b, #c').changeBackgroundColor('getColor'));

$('#a').changeBackgroundColor('setColor', 'red');
console.log($('#a').changeBackgroundColor('getColor'));

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Define your method like this

$.fn.getColor = function() { 
     alert('getColor called'); 
}

Basic Custom Plugin

Upvotes: 0

Related Questions