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()
In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:
Note that the
$
in the variable name$param
is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just useparam
as well.While there is a plethora of documentation / tutorials out there, the simple answer for your question is this:
Inside that function, the
this
variable corresponds to the jQuery wrapped set you called your function on. So something like:... will flush to the console the number of elements with the class
foo
.Of course, there is a bit more to semantics than that (as well as best practices, and all that jazz), so make sure you read up on it.
To make a function available on jQuery objects you add it to the jQuery prototype (fn is a shortcut for prototype in jQuery) like this:
This is usually called a jQuery plugin.
Example - http://jsfiddle.net/VwPrm/
Yes, methods you apply to elements selected using jquery, are called jquery plugins and there is a good amount of info on authoring within the jquery docs.
Its worth noting that jquery is just javascript, so there is nothing special about a "jquery method".
From the Docs:
Then you do
You can write your own jQuery plugins(function which can be called on selected elements) like below:
Call it later like: