0Pricing
jQuery Academy · Lesson

Building Configurable and Reusable Plugins

Develop plugins with default options, allowing users to override settings, and make them reusable across different projects with minimal effort.

Building Configurable and Reusable Plugins is a free jQuery Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Configurable Plugins Intro

Welcome! In this lesson, you'll learn how to make your jQuery plugins flexible and easy to adapt. Imagine a plugin that can change its color, speed, or text just by providing a few options.

This is crucial for creating tools that can be used in many different projects without needing to rewrite code.

Why Use Default Options?

Plugins should work out-of-the-box, but also allow customization. This is where default options come in.

  • Baseline behavior: Provides a standard way the plugin acts.
  • Ease of use: Users can initialize the plugin without specifying every setting.
  • Flexibility: Users can override defaults to tailor the plugin to their needs.

Defining Plugin Defaults

You define default options as an object inside your plugin. This object holds all the settings your plugin might use, along with their initial values.

Try running this basic plugin structure to see how defaults are declared.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="myElement">Hello</div>
<script>
(function($) {
  $.fn.myPlugin = function(options) {
    // Define default settings here
    var defaults = {
      color: "blue",
      fontSize: "16px",
      message: "Default message!"
    };
    
    // For now, let's just log the defaults
    console.log("Plugin defaults:", defaults);
    
    return this; // Always return 'this' for chaining
  };
})(jQuery);

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

Merging User Options: $.extend()

To allow users to customize settings, you need to merge their provided options with your defaults. jQuery's $.extend() method is perfect for this.

$.extend({}, defaults, options) creates a new object, copying properties from defaults first, then overwriting them with properties from options if they exist.

$.extend() in Action

Here's how you use $.extend() within your plugin. Notice how the user's color and text override the defaults, but fontSize remains from defaults because it wasn't provided.

Run this code and check the console output!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
(function($) {
  $.fn.myPlugin = function(options) {
    var defaults = {
      text: "Default text",
      color: "blue",
      fontSize: "16px"
    };
    
    // Merge defaults with user-provided options
    var settings = $.extend({}, defaults, options);
    
    console.log("Final settings:", settings);
    
    return this; // Keep chaining ability
  };
})(jQuery);

$(document).ready(function() {
  // User provides custom options
  $('body').myPlugin({
    text: "Custom Text!",
    color: "red"
  });
});
</script>

Accessing Merged Settings

Once you have your settings object (which contains the merged defaults and user options), you can simply access any property using dot notation, like settings.color or settings.animationSpeed.

This ensures your plugin always uses the correct, final configuration.

Practical Tooltip Plugin

Let's build a simple tooltip plugin that allows users to customize its text, background color, and the delay before it appears. This demonstrates how configurable options make plugins much more versatile.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<style>
  .coddy-tooltip { /* Use unique class name */
    position: absolute;
    background-color: #333;
    color: white;
    padding: 5px 8px;
    border-radius: 3px;
    display: none;
    font-family: sans-serif;
    font-size: 14px;
  }
</style>
<button id="hoverMe">Hover Over Me</button>
<script>
(function($) {
  $.fn.coddyTooltip = function(options) {
    var defaults = {
      text: "Default Tooltip",
      bgColor: "#333",
      textColor: "white",
      delay: 200 // ms before showing
    };
    var settings = $.extend({}, defaults, options);

    return this.each(function() {
      var $this = $(this);
      var $tooltip = $('<div class="coddy-tooltip"></div>')
                       .text(settings.text)
                       .css({
                         'background-color': settings.bgColor,
                         'color': settings.textColor
                       })
                       .appendTo('body');

      var timeoutId; // To clear previous timeouts

      $this.on('mouseenter', function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
          var offset = $this.offset();
          $tooltip.css({
            top: offset.top - $tooltip.outerHeight() - 5,
            left: offset.left + ($this.outerWidth() / 2) - 
                   ($tooltip.outerWidth() / 2)
          }).fadeIn(100);
        }, settings.delay);
      }).on('mouseleave', function() {
        clearTimeout(timeoutId);
        $tooltip.fadeOut(100);
      });
    });
  };
})(jQuery);

$(document).ready(function() {
  // Initialize the tooltip with custom options
  $('#hoverMe').coddyTooltip({
    text: "Hello from CoddyKit!",
    bgColor: "darkblue",
    delay: 500
  });
});
</script>

Designing for Reusability

Beyond configuration, a truly robust plugin is reusable. This means it can be dropped into any project and work without conflicts or specific setup.

  • Encapsulation: Use an IIFE (function($){...})(jQuery); to keep your code private.
  • `this.each()`: Always iterate over selected elements to apply logic to all matched items.
  • No global pollution: Avoid creating global variables or functions.
  • Self-contained logic: Your plugin should not depend on external scripts or styles unless explicitly documented.

The Importance of `this.each()`

When a user calls your plugin on a selection like $('.my-class').myPlugin(), jQuery might return multiple elements. The return this.each(function(){ ... }); pattern ensures your plugin's logic runs for each individual element in that selection.

Inside the each callback, this refers to the current DOM element being processed.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<script>
(function($) {
  $.fn.highlight = function(options) {
    var defaults = {
      color: "yellow"
    };
    var settings = $.extend({}, defaults, options);

    return this.each(function() {
      // 'this' refers to the current DOM element in the loop
      $(this).css('background-color', settings.color);
    });
  };
})(jQuery);

$(document).ready(function() {
  // Apply highlight to all elements with class 'item'
  $('.item').highlight({ color: "lightblue" });
});
</script>

Quick Check: Plugin Best Practices

Let's test your understanding of building configurable and reusable jQuery plugins!

Recap: Configurable & Reusable

You've mastered how to build powerful, adaptable jQuery plugins!

  • Define default options for baseline behavior.
  • Use $.extend() to merge user options, allowing customization.
  • Employ return this.each() to ensure your plugin works on multiple selected elements.
  • Encapsulate your code in an IIFE for reusability and to avoid global conflicts.

These techniques make your plugins robust, flexible, and ready for any project!

Frequently asked questions

Is the “Building Configurable and Reusable Plugins” lesson free?

Yes — the full text of “Building Configurable and Reusable Plugins” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.

What will I learn in “Building Configurable and Reusable Plugins”?

Develop plugins with default options, allowing users to override settings, and make them reusable across different projects with minimal effort. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start jQuery Academy?

No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Building Configurable and Reusable Plugins” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this jQuery Academy lesson?

Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Plugin Design Patterns and Scoping
  2. Building Configurable and Reusable Plugins
  3. Integrating Public Methods and Callbacks
← Back to jQuery Academy