Add properties and methods to jQuery plugins

Add properties and methods to jQuery plugins

How to add public properties and methods to jQuery plugins.

jQuery elements are objects so it should be theoretically possible to add methods and properties to them. jQuery plugins work by extending a jQuery object with custom functionalities. They're the perfect place where we can extend a jQuery element object with custom methods and properties.

The object is currently referred by the this keyword. This keyword points to the current element where a plugin is attached to. Knowing this, we can define public methods and properties for our plugin:


(function($) {
    $.fn.plugin = function(options) {

        var self = this;
        var defaults = {
            test: 'Foo',
            bar: 'Baz'
        };

        options = $.extend(defaults, options);


        self.property = 'Test';
        self.method = function() {
            console.log(self.property);
            console.log('Method called');
        }



        return self.each(function() {
            self.property = options.test + ' ' + options.bar;

            $(self).on('click', self.method);

        });
    };
})(jQuery);

We've defined a method and a property. The property's value will be set to both values found in the plugin's options object. The plugin's method will be fired when a user clicks on the attached element.

Our code can either work indirectly on user's click:


$('#test').plugin(); // 'Foo Baz' 'Method called'

or can be called directly like this:


console.log($('#test').plugin().property); // 'Foo Baz'

Being bound to this, our methods and properties work from outside only when the plugin's code has been instantiated. If you try to access them as $(element).plugin.property, you'll get an error. Remember that plugins are basically functions, and functions are first-class citizen JavaScript objects.

You can see the demo on this page.