Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

plugins

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?

like image 763
User Avatar asked Feb 11 '09 18:02

User


1 Answers

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
like image 71
Pim Jager Avatar answered Nov 15 '22 07:11

Pim Jager