Learn How To Create Custom jQuery Plugins

jQuery is a JavaScript framework that makes Event Handling and DOM manipulation easy. Though, jQuery provides many built-in APIs for manipulating DOM elements there are times when you might want create your own methods for manipulating DOM elements. In this article we will talk about creating custom jQuery plugins.

jQuery Plugins are nothing but extension methods to jQuery object protoype. jQuery provides a minimal interface to create extension methods.

In this post we will create a jQuery plugin that resizes an element based on its parent’s width.

$(function() {
  $.fn.resize = function() {
    $this = $(this);
    $this.each(function() {
      var parentWidth = $(this).parent().width();
      var elementWidth= $(this)[0].scrollWidth;
      var currentFontSize = parseFloat($(this).css("font-size"));
      if(elementWidth > parentWidth) {
        var recommendedFontSize = Math.floor(currentFontSize *   (parentWidth/ elementWidth));      
        $(this).css("font-size", recommendedFontSize);
      }      
    });
  };  
});

Explained: Custom jQuery Plugins Syntax

  1. $.fn is an alias for jQuery prototype and hence by the statement $.fn.resize you are extending the prototype of jQuery with a new function.
  2. In the function resize $(this) points to all elements matching the selector passed at the time of calling resize();

One thought on “Learn How To Create Custom jQuery Plugins

Leave a Reply

Your email address will not be published. Required fields are marked *