MacMac
MacMac

Reputation: 35301

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();.

Upvotes: 5

Views: 2573

Answers (3)

Shishir Arora
Shishir Arora

Reputation: 5923

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

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125488

You use

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

            // code

})(jQuery);

This is an immediately executed anonymous function that takes one argument and is bound to parameter, $, to which a value, jQuery, is supplied.

Upvotes: 2

user113716
user113716

Reputation: 322492

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.

Upvotes: 6

Related Questions