mushroom
mushroom

Reputation: 1945

jQuery Plugin Authoring

Any idea why this basic example doesn't work?

http://jsfiddle.net/Kq6pz/

(function( $ ){

  $.fn.testPlugin = function( options ) {  
        alert('hi');
  };
})( jQuery );

$.testPlugin();

Upvotes: 2

Views: 230

Answers (2)

Chad
Chad

Reputation: 19609

Because you added your plugin to the fn namespace not to the $ namespace. So $().testPlugin() will work but $.testPlugin() does not.

If you want to pollute the $ namespace you can do:

(function( $ ){

  $.testPlugin = function( options ) {  
        alert('hi');
  };
})( jQuery );

$.testPlugin();

My rule of thumb I follow is: use $. when it is not DOM related (like ajax), and use $.fn. when it operates on elements grabbed with a selector (like DOM/XML elements).

Upvotes: 5

Dom
Dom

Reputation: 40459

You need a selector:

$(document).testPlugin();
$(window).testPlugin();

DEMO: http://jsfiddle.net/dirtyd77/Kq6pz/1/

Upvotes: 1

Related Questions