jQuery: Plugin Development - Global Functions

As we know, jQuery open for other developers. Yes, we can write code that could be reused by other. We may want to package it up as a new plugin. This make jQuery have very rich library. Now, we will learn how to create jQuery plugin. We start with plugins that simply make new global function available.

Adding new global function

To learn jQuery plugin development, we must know about global function. jQuery have built-in capibilities via facility what we have been calling global function. These are methods of jQuery, but the are functions within a jQuery namespace.

To add a function to the jQuery namespace, just add new function as property of the jQuery object:

jQuery.globalFunction = function() {
  alert('Hi.. just test');

To use it, we can write:


We also write using $:


Create Multiple Functions

If we need more than one global function, we must declare them independently:

jQuery.functionOne = function() {
  alert('Hi... I am fist');
jQuery.functionTwo = function(param) {
  alert('Hi... I am "' + param + '".');

We can call them:


We can also use $.extend() function as alternate syntax to define our function:

  functionOne: function() {
    alert('Hi...I am first');
  functionTwo: function(param) {
    alert('Hi.. I am "' + param + '".');

Avoiding function names conflict

To avoid function name conflict, we must encapsulate all of the global function for a plugin into an object

jQuery.myPlugin = {
  functionOne: function() {
    alert('Hi...I am first');
  functionTwo: function(param) {
    alert('Hi...I am "' + param + '".');

To call, we have to the plugin name:


Creating a Utility Method

Utility method are shortcuts for the tasks that are frequently needed. For example, we will create $.sum() function to total number.

jQuery.sum = function(array) {
  var total = 0;
  jQuery.each(array, function(index, value) {
    total += value;
  return total;

Example using:

$(document).ready(function() {
	var myArray = [3, 5, 7, 9];
	var total   = $.sum(myArray);

Bookmark and Share Tag: jquery, JavaScript, JavaScript Framework Category: JavaScript Post : September 12th 2010 Read: 19,495


blog comments powered by Disqus