User
User

Reputation: 3782

jQuery Plugin Authoring: Why do some do jQuery.pluginName and others jQuery.fn.pluginName?

For example, I'm looking at the jCalendar source, and the creator has two different parts of the plugin, one function under "jQuery.jcalendar" and another "jQuery.fn.jcalendar". What is the purpose of having the two separated? What one do over the other?

Upvotes: 5

Views: 2289

Answers (1)

Pim Jager
Pim Jager

Reputation: 32129

jQuery.fn.mypluging name extends jQuery objects:

$(selector); //a jquery object
$(selector).myplugin();

jQuery.myplugin extends the jquery object itself:

$; //the jQuery object
$.myPlugin();

By adding your plugin to jQuery.fn you can do stuff to the objects found by that selector:

jQuery.fn.makeRed = function(){
 this.each( function() {
  $(this).css('color', 'red');
 }
}

$('div.someClass').makeRed(); //makes all divs of class someclass have red text

Extending the jQuery object itself is ussually done for functions that your class needs but that do not extend jQuery objects. So to extend our previous example:

jQuery.fn.doStuff = function(){
 this.each( function() {
  $(this).css('color', 'red')
         .append($.doStuff.giveMeRandom());
 }
}

jQuery.doStuff = {
 giveMeRandom: function() {
  return Math.random();
 }
}

$('div.someClass').doStuff(); //makes all divs of class someclass have red text and append a random number to them

Upvotes: 10

Related Questions