Preparing the plugin to use $ .plugin () instead of $ (selector) .plugin ()

Simply:

(function($){
    $.fn.plugin = function()
    {
        // results in error
        // when called like
        // $.plugin();
    }
})(jQuery);

Error (copied from the Chrome console):

Uncaught TypeError: Object function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } has no method 'plugin'

What rules should I follow to make my plugin without selecting an item?

+3
source share
3 answers

Just assign the function directly $.plugin:

(function($){
    $.plugin = function()
    {
        // ...
    }
})(jQuery);

Of course, thisit will no longer refer to the selected items, but to jQuery.

+6
source

The problem is that you declared the plugin as a method of the $ .fn object and are trying to access the plugin as a jQuery Object method

0
source

Keep the jQuery conventions and prefer to use it this way:

$(this).plugin()
0
source

All Articles