By “custom function” I am assuming you mean “plugin”. If that’s the case, there is a good tutorial on the jQuery site. The basic idea is this:
(function($) {
$.fn.myPlugin = function() {
return this.each(function() {
//Do stuff
});
};
}(jQuery));
Basically, the code above does a few things. Firstly, it captures the value of jQuery
and passes it into an anonymous function where it can then be referred to as $
(this is so that users of your plugin who happen to be using the $
identifier for something else can still use it.)
It then declares a method on $.fn
, which is just an alias for $.prototype
. Inside that method, this
refers to the matched set of elements on which the plugin has been called. Since thats a jQuery object, and may contain multiple elements, you need to iterate over that set (that’s why the each
is there).
The return
statement is used to maintain chainability of the plugin with other jQuery methods. Since each
returns an instance of jQuery, the plugin itself returns an instance of jQuery, and other jQuery methods can obviously be called on an instance of jQuery.