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()
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()
Yup — what you’re describing is a jQuery plugin.
To write a jQuery plugin, you create a function in JavaScript, and assign it to a property on the object
jQuery.fn
.E.g.
Within your plugin function, the
this
keyword is set to the jQuery object on which your plugin was invoked. So, when you do:Then
this
insidemyfunction
will be set to the jQuery object returned by$('#my_div')
.See http://docs.jquery.com/Plugins/Authoring for the full story.