0

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....:)

3 Answers 3

1

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'));
Sign up to request clarification or add additional context in comments.

Comments

0

Define your method like this

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

Basic Custom Plugin

6 Comments

You can define it in your custome plugin or if you are going to use it in your html page only then you can define it in that page.
See basic custom plugin for your reference.
@bhushan...getting error on div1.getColor() -> undefined is not a function. Thanks
check if div1 is undefined or null
@bhushan...anything wrong in this code? var div1 = $("#div1").changeBackgroundColor({ color: $('#colorCode').val().trim() }); div1.getColor();
|
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.