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()
You can always do this:
You can also use extend (the way you create jQuery plugins):
Usage:
It sounds like you want to extend the jQuery object via it's prototype (aka write a jQuery plugin). This would mean that every new object created through calling the jQuery function (
$(selector/DOM element)
) would have this method.Here is a very simple example:
Demo
Simplest example to making any function in jQuery is
Create a "colorize" method:
Use it:
This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.
this
may be chained. (Thanks @Potheek.)