Creating a jQuery Plugin

Any idea why this basic example is not working?

http://jsfiddle.net/Kq6pz/

(function( $ ){ $.fn.testPlugin = function( options ) { alert('hi'); }; })( jQuery ); $.testPlugin(); 
+2
source share
2 answers

Since you added your plugin to the fn namespace not to the $ namespace. Thus, $().testPlugin() will work, but $.testPlugin() does not work.

If you want to foul the $ namespace, you can do:

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

The following is my rule: use $. if it is not related to the DOM (e.g. ajax) and use $.fn. when it works with elements captured by a selector (e.g. DOM / XML elements).

+5
source

You need a selector:

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

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

+1
source

All Articles