Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 209
MacMac Avatar asked Feb 25 '11 18:02

MacMac


People also ask

What does empty() do in jQuery?

The empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method. Tip: To remove the elements and its data and events, use the remove() method.

How to use empty in JavaScript?

The empty statement is a semicolon ( ; ) indicating that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one.


2 Answers

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.

like image 56
user113716 Avatar answered Oct 07 '22 00:10

user113716


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.

like image 27
Russ Cam Avatar answered Oct 06 '22 23:10

Russ Cam