Why We Develop jQuery Plugins

jQuery is one of the most popular JavaScript libraries among web developers and designers. And, many new plugins with amazing effects are created every day. Developers and users tend to select jQuery plugins whenever possible. If you’re still on the fence about jQuery, this article will help you understand why they are so popular.

A plugin is an independent module that adds custom functionality to an application. Enabling or disabling a plugin does not affect the core system or other plugins. As developers, we tend to look for quick fixes rather than focusing on maintainable solutions. With experience we change our approach to consider maintainability and future enhancements. To understand why plugins are such an attractive option, we must first understand what life would be like without them.

Developing Without Plugins

Assume that we have been given the task of converting a menu comprised of unordered lists into a select box. This will be a very handy feature to have in our responsive web design toolkit. So, we are going to use it as our base example for understanding why we develop jQuery plugins. Let’s look at a basic jQuery implementation.

<script>
$(document).ready(function(){
  var select = $('<select>');
  $('#menu li').each(function() {

    var link  = $(this).find('> a');
    var level = $(this).parents('li').length;

    var indent = '';
    for(i=0;i<level;i++){
      indent += '-';
    }

    var option = $('<option>').text(indent + ' ' + link.text())
       .val(link.attr('href'))
       .appendTo(select);
  });

  $('#menu').replaceWith(select);
});
</script>

The code snippet above converts the unordered list items into options inside a select box. You can see that the unordered list ID is hard coded. If we wanted to convert another list to a select box, we would have to duplicate the existing code, which can be error prone. Instead, we convert the code into a function to make it reusable. The code should be similar to the following:

<script>
function convertMenusToSelect(menu){
  // Previous code with dynamic item instead of hard coding #menu
}
</script>

Now, we have a common function that we can reuse over and over again. But, suddenly a new customer requirement comes in with the following two tasks.

  • Selected menu options should be highlighted in a given color.
  • The indentation sign used for the sub menus should be dynamic.

The immediate solution would be to add another two parameters to the convertMenusToSelect() function to handle both color and indentation sign. However, as more requirements comes in, we will have to add additional parameters, making it hard to maintain. Instead, we can consider passing parameters as an object, as shown below.

<script>
function convertMenusToSelect(params){

}

var params={menuID: '#menu', color:'#EEE', indentMark : '#' };
convertMenusToSelect(params);
</script>

There can be both mandatory and optional parameters within the object, so we need to check for the parameters manually in order to extract the correct values. As new requirements comes in, our solution is becoming very hard to maintain. So, let’s look at a solution using a jQuery plugin and see how it handles the changing requirements.

Developing With jQuery Plugins

We started the list-to-select box converter with plain jQuery code, and converted it to a reusable function in the process. Now, let’s look at a jQuery plugin implementation using the following code.

<script>
(function($){
  $.fn.extend({
    selectConvert: function(options) {
      var defaults = {
        color: '#EEE',
        indentMark: '-',
      }

      var options =  $.extend(defaults, options);

      this.each(function() {
        var o = options;
        var currentItem = $(this);
        var select = $('<select>');

        $(currentItem).find('li').each(function() {
          var link  = $(this).find('> a');
          var level     = $(this).parents('li').length;
          var indent = '';
          for(i=0;i<level;i++){
            indent += o.indentMark;
          }

          var option = $('<option>').text(indent + ' ' + link.text())
            .val(link.attr('href')).css('background',o.color)
            .appendTo(select);
        });

        $(currentItem).replaceWith(select);
        return select;
      });
    }
  });
})(jQuery);
</script>

In the above code selectConvert will be our plugin name, and will be a separate namespace inside the jQuery.fn object. Each of the plugin methods will be placed inside the selectConvert() function. The plugin function uses a variable called options to handle the data passed on initialization. The defaults variable contains all of the allowed variables and their default values. We can also assign functions to the defaults section.

Then, we compare the defaults against the options passed to the plugin using the jQuery extend() function. The final output will contain the passed option values and default values which are not provided in the initialization. Hence, adding new parameters is not such a difficult task with jQuery plugins. Finally, we execute the conversion code with the provided options and returns the converted item.

The Importance of jQuery Plugins

We made the decision to implement a plugin due to the issues we had with the plain jQuery implementation. Now, let’s see why we prefer jQuery plugins over pure JavaScript implementations.

  • Prevents Function Conflicts

    We create all the plugin related functions inside a unique namespace. So, the possibility of name conflicts is reduced with plugins.

  • Extendability

    jQuery plugins automate the process of extending parameters and functions within the plugin. We can define the default parameters and functions inside the plugin and override them at runtime using extended values and functions. This reduces the work of handling required and optional parameters.

  • Chainability

    I would assume chainability is the most powerful factor in jQuery plugins. In pure JavaScript we have to call functions, assign the results to variables, and pass them to the next function. With jQuery, we can call another function or plugin on the same returned results in one line of code. Consider the following code, which combines a jQuery autocomplete select box plugin with our design. You can chain together any number of functions or plugins on the same result set, making it easy to add and remove functionality dynamically.

    <script>
    $(document).ready(function() {
      $('#menu').selectConvert().combobox();
    });
    </script>
    
  • Reusability

    jQuery plugins allows us to use the same functionality over multiple elements without duplicating code. We used a single menu in our initialization code as shown below.

    <script>
    $(document).ready(function() {
      $('#menu').selectConvert();
    });
    </script>
    

    Generally, we need to use two lines for converting two menus. But jQuery makes is possible to reuse the same line of initialization code for both menus as shown in the following code.

    <script>
    $(document).ready(function() {
      $('#menu,#menu2').selectConvert();
    });
    <script>
    
  • Encapsulation

    We can define both public and private functions inside a jQuery plugin. Therefore, we can encapsulate the logic inside the plugin and decide which components are publicly visible and which are private to the plugin. So, plugin developers and users will only be able to call features publicly available.

  • Usability

    Most of the people who uses jQuery plugins are not very experienced with JavaScript or jQuery. As developers, we need to make it as simple as possible to use the plugins. jQuery plugins provides a common initialization technique, where you can call the plugin initialization function on any compatible element. Therefore, users can just copy the initialization code and everything will work.

Conclusion

We have used one of the most basic patterns of jQuery plugins in this tutorial. There are also several advanced patterns which make it even easier to write highly maintainable and extendable code. As a developer, you might be wondering why we can’t do the same with plain JavaScript. jQuery is built using JavaScript, so JavaScript is capable of providing anything jQuery provides. However, we prefer to use jQuery since it abstracts many common tasks and allows us to focus on application logic.

It’s time to share your opinion on jQuery plugins vs pure JavaScript implementation. Do you prefer developing and using jQuery plugins? Let us know. You can also download the code used in this article from the JSPro GitHub page.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • tcoulson

    couldn’t $(currentItem). be written as just currentItem, and all the places you have $(this) be replaced with currentItem since you assigned the variable? I thought it is not a good idea to call $(this) in multiple places because it forces jquery to call the dom each time for a lookup? Otherwise, loved the article. Thanks.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hello tcoulson

      Thanks for pointing it out. I could have gone with currentItem instead of $(currentItem) . I dont think it’s a good idea to call $(this) every time as well. So I have assigned it to a variable called currentItem.

      You suggested to use the same variable across all $(this) statements. Actually first $(this) which I have assigned to currentItem refers to UL element and next $(this) staments refers to LI element. So we cannot use the same variable across all instances. But I could have assigned the other $(this) statements to another variable called currentLI. I hope this clear your concerns.

      Let me know if you have further questions.

      Thanks.

  • Nathar Leichoz

    What’s the difference between a jQuery plugin and a plugin that uses jQuery?

    I’d imagine the majority of jQuery plugins are really just plugins that use jQuery.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hello Nathar

      Thanks for your comment.

      What exactly did you mean by plugins that use jQuery ? Can you please explain further with probably with an example ?

      Looking forward to hear from you.