2

When I look at the JQuery plugin code, it almost seems to me that we are creating a function (although we use the JQuery.fn syntax) Functionally, what's a difference between a function and a plugin?

DotnetDude
  • 11,617
  • 35
  • 100
  • 158
  • possible duplicate of [jquery - difference between $.functionName and $.fn.FunctionName](http://stackoverflow.com/questions/2845981/jquery-difference-between-functionname-and-fn-functionname) – redsquare Sep 27 '10 at 23:18
  • @redsquare - I disagree that this is a duplicate, he's asking about a function, not a function on the jQuery object, that's a much more narrowly scoped question you linked as a dupe...and it usually has a much narrower and specific purpose. – Nick Craver Sep 28 '10 at 00:19

3 Answers3

6

A function is just a normal JavaScript function, for example:

function doSomething(param) {
  alert(param);
}

A plugin is intended to be run on a set of elements, for example:

jQuery.fn.plugin = function(param) {
  return this.attr('something', param);
}

This would set the 'something' attribute on all elements it was called on, like this:

$('.selector').plugin('value');

If you intend to use the function on a set of elements, like in a jQuery chain, then a plugin may be the answer for you...if you're just calling a function and doing stuff, really having nothing to do with a set of elements, use a plain named function.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
3

Basically a jQuery plugin is a function that is meant to extend jQuery's functionality, and can be applied to selectors more "naturally" than regular functions.

bevacqua
  • 47,502
  • 56
  • 171
  • 285
0

The difference is that using $.fn means you can call the function chained onto any jQuery object

Gareth
  • 133,157
  • 36
  • 148
  • 157