Writing A Simple Jquery Plugin

Jquery is a fantastic Javascript library that makes manipulating the DOM a breeze. Its usefulness lies in the powerful selectors which make it easy to pick which part of the DOM you want to work with, and many functions with which to manipulate the selected objects.

Jquery provides a lot of functionality, but like any good library, also provides the ability to easily extend its capabilities. I recently found it useful to do this, so here’s a quick run down on how to do just that.

The Barebones

To start with we’ll just put together a bare plugin so that we can see the structure:

(function($) {
  $.fn.mask = function() {
  //body goes here
  };
})(jQuery);

This adds a new function, mask, to the jquery object. You could use it like so:

  $('#objectToMask').mask();

An Overlay

The reason I started to look into this was that I wanted to encapsulate a piece of functionality that would allow an overlay mask to be applied to an arbitrary element. This is useful when loading something asynchronously to let the user have some visual feedback.

Firstly the mask function:

(function($) {
  $.fn.mask = function() {
    if ($("#overlay").length == 0) {
      var $overlay = $('<div id="overlay"><img src="images/loader.gif" id="img-load" /></div>');
      $("body").append($overlay);
    }

    $("#overlay").css({
      opacity: 0.5,
      top: this.offset().top,
      left: this.offset().left,
      width: this.outerWidth(),
      height: this.outerHeight()
    });

    $("#img-load").css({
      top: (this.height() / 2),
      left: (this.width() / 2)
    });

    $("#overlay").fadeIn();
  };
})(jQuery);

This is pretty straight forward; We create the overlay element if it doesn’t exist, set its position along with the loading image position, and then fade it in.

The unmask function, is shorter, as it just needs to hide the element:

(function($) {
  $.fn.unmask = function() {
    $("#overlay").fadeOut();
  };
})(jQuery);

Summary

And that’s all there is to it. Extending Jquery is a relatively simple and straightforward process that’s well worth investigating when you want to encapsulate a piece of functionality to make it easily reusable.