Empty selector - Creating a jQuery plugin

How do you create a plugin that does not require a selector, for example:

$.pluginName();

From this:

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

    // code

})(jQuery);

Instead of using this (to prevent other libraries from colliding $):

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

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

+5
source share
3 answers

Put it in global jQuery instead of prototype.

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

    // code

})(jQuery);

Keep in mind that thisinside your function there will not be a jQuery object. It will reference a global function jQuery.

+6
source

You're using

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

            // code

})(jQuery);

, $, jQuery.

+2

you can also use $ .extend ({f1: function () {}, f2: function () {}}) if you want to add more than 1 plugin together. this will make ur code look cleaner.

0
source

All Articles