Search code examples
jquerypluginsjquery-pluginsextend

Empty selector - jQuery Plugin Creation


How do you create a plugin that does not require a selector, e.g:

$.pluginName();

Out of this:

(function($)
{
    $.fn.pluginName = function(options) 
    {
            // options
    };

    // code

})(jQuery);

Instead of using this (to prevent other libraries clashing with the $):

jQuery.pluginName = function(name, value, options) 
{
   // code
};

Since if I do this: $.pluginName(), Firebug tells me that $.pluginName() is not a function unless I add this: $.('a selector goes here').pluginName();.


Solution

  • Place it on the global jQuery instead of the prototype.

    (function($)
    {
    //---v----------------namespacing your function in the jQuery namespace
        $.pluginName = function(options) 
        {
                // options
        };
    
        // code
    
    })(jQuery);
    

    Keep in mind that this inside your function will not be a jQuery object. It will refer to the global jQuery function.