Learn to create a basic jQuery plugin easily

How to create a jQuery plugin

jQuery is being used around 60.000.000 sites, it has become a fundamental library that every website should use due to its simplicity and performance.

The following simple structure will define our jQuery plugin and we will be ready to create our custom functions.

(function($){
	$.fn.extend({
            // an object with our functions
        });
})(jQuery);

The strucure is almost the same that a normal library, but instead of receive the window object, we will receive jQuery. Note that you need obviously , load jQuery before your plugin.

jQuery is object oriented, therefore our functions will have the name that we give to the key of the object, for example :

{
  // This will paint the background color of a div with our given value.
  myCustomAlert:function(color){
      this.css({
         backgroundColor:color
      });
  }
}

// Then we will call it like this :

$('#myselector').myCustomAlert('red');

If your plugin doesn't need a selector but anyway needs jQuery, you can create a property for jQuery with your function, for example

var createAlert = {
   showAlert : function(){
      // The code that will show the alert
   },
   hideAlert : function(){
      // the code that will hide the alert
   }
};

$.myCustomAlert = createAlert;
// or if you want jQuery instead $
jQuery.myCustomAlert = createAlert;

// Then execute your plugin like this

$.myCustomAlert.showAlert();

That's all that you need to know when you want to create your own jQuery plugin. Now let's create something more complicated !

The following plugin will execute a function after every x miliseconds after the last keyup event, this function can be useful when you want to create an autocomplete or to increase the performance of a function that is executed everytime the user press a key. Play with the following fiddle, the source code can be viewed in the javascript tab.

Have fun and create your own jQuery plugin !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors