How to add a function to jQuery?

Solution 1:

Please see "Defining your own functions in jQuery" by Basil Goldman:

In this post, I want to present how easy define your own functions in jQuery and using them.

Modified, based on the code in the blog post linked above:

jQuery.fn.yourFunctionName = function() {
    // `this` is the jQuery Object on which the yourFunctionName method is called.
    // `arguments` will contain any arguments passed to the yourFunctionName method.
    var firstElement = this[0];

    return this; // Needed for other methods to be able to chain off of yourFunctionName.
};

Just use:

$(element).yourFunctionName();

Solution 2:

This is the pattern that I prefer to define my own plugins.

(function($) {

    $.fn.extend({
        myfunc: function(options) {
            options = $.extend( {}, $.MyFunc.defaults, options );

            this.each(function() {
                new $.MyFunc(this,options);
            });
            return this;
        }
    });

    // ctl is the element, options is the set of defaults + user options
    $.MyFunc = function( ctl, options ) {
         ...your function.
    };

    // option defaults
    $.MyFunc.defaults = {
        ...hash of default settings...
    };

})(jQuery);

Applied as:

$('selector').myfunc( { option: value } );