Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery plugin best practice

I'm new to jQuery plugin development and I'm interesting to know, about what's difference between two ways listed below? And what's the right way to do this?

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

And the second one:

(function($){
  $.fn.myPlugin = function() {
    // plugin code 
  };
})(jQuery);
like image 792
WarGasm Avatar asked Dec 27 '22 00:12

WarGasm


1 Answers

The first one adds a utility function to jQuery, which would be called as $.myplugin(...).

The second one adds a plugin which acts on jQuery objects, which would be called as $(selector).myPlugin(...)

Choose the latter if you're working on a plugin which acts on elements, and can be part of a jQuery-style "chain" of function calls.

like image 122
Alnitak Avatar answered Jan 12 '23 16:01

Alnitak