5 July 2010

Tutorial about creating your own functions using jQuery JavaScript library.

JavaScript library jQuery provides you with loads of functions that you can use to simplify your work. There are also many plugins available that are made by users. Still time to time you might have to create some of your own. Or you need something specific and don’t want to waste you bandwidth for big plugins from witch you use only one function. For the starters you might want to make the function jQuery way, because you do want to use as much as possible from that library, even when defining just a function.

Define a Function:

This structure reminds me classes. Function name is class name and "sub_function_name" is function. I would place this code to *.js file and include the file to my html file, so it wouldn't bloat.
Source code viewer
  1. (function($) {
  2. $.function_name = {
  3. //Define Parameters
  4. string_name: "value",
  5. //Sub Function
  6. sub_function_name: function(){
  7. //Your Code
  8. }
  9. };
  10. })(jQuery);
Programming Language: jQuery

Call the Function:

This way you can call the function from your html code. Of course put this in script tags if you add it to your html file:
Source code viewer
  1. $(document).ready(function(){
  2. $.function_name.sub_function_name();
  3. });
Programming Language: jQuery