How to create a jQuery function (a new jQuery method or plugin)?

multimediaxp picture multimediaxp · Aug 23, 2012 · Viewed 580.2k times · Source

I know that in JavaScript the syntax is as follows:

function myfunction(param){
  //some code
}

Is there a way to declare a function in jQuery that can be added to an element? For example:

$('#my_div').myfunction()

Answer

Candide picture Candide · Aug 23, 2012

From the Docs:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

Then you do

$('#my_div').myfunction();