4

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);
khellang
  • 17,550
  • 6
  • 64
  • 84
WarGasm
  • 327
  • 2
  • 12
  • possible duplicate of [jquery - difference between $.functionName and $.fn.FunctionName](http://stackoverflow.com/questions/2845981/jquery-difference-between-functionname-and-fn-functionname) – Pranay Rana May 16 '12 at 08:10

2 Answers2

8

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 2
    +1 A list of jQuery Utilities can be found here: http://api.jquery.com/category/utilities/ It's also worth mentioning that to make the jQuery object plugin chainable you must return the jQuery object referenced as `this`. – iambriansreed May 16 '12 at 08:06
  • Technically it's `$(this)` but I am sure you know *this*. – iambriansreed May 16 '12 at 08:10
  • @iambriansreed nope, actually just `this` - in a `$.fn` extension `this` is _already_ a jQuery object. – Alnitak May 16 '12 at 08:14
  • Argh. Why is it different only in plugins!?. http://docs.jquery.com/Plugins/Authoring So getting to the DOM element would be `this[0]`, correct? – iambriansreed May 16 '12 at 08:16
  • @iambriansreed plugins often just do `return this.each(function() { ... })` so the DOM element is then just available as `this` inside _that_ closure. – Alnitak May 16 '12 at 08:19
  • Cool. I think I have seen that. Thanks! – iambriansreed May 16 '12 at 11:07
  • @iambriansreed it's in section 4 of the link you posted... ;-) – Alnitak May 16 '12 at 11:27
2

$.fn points to the jQuery.prototype. Any methods or properties you add to it become available to all instance of the jQuery wrapped objects.

$.something adds a property or function to the jQuery object itself.

Use the first form $.fn.something when you're dealing with DOM elements on the page, and your plugin does something to the elements. When the plugin has nothing to do with the DOM elements, use the other form $.something

similar questions :-)

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263