How to Pass Options to a jQuery Plugin

Making a jQuery plugin customizable requires allowing users to pass a configuration or options object to override default behaviors. This guide demonstrates how to define default settings, use jQuery's built-in $.extend() method to merge user-provided arguments with those defaults, and maintain proper jQuery chaining throughout your plugin implementation.

The Role of $.extend()

The core mechanism for handling an options object in jQuery is the $.extend() method. It merges the contents of two or more objects into a target object. When designing a plugin, you pass an empty object {} as the target, followed by your default settings object, and finally the user-supplied options object. This ensures your base defaults remain untouched while cleanly applying any overrides.

var settings = $.extend({}, defaults, options);

Complete Implementation

Wrap your plugin logic inside an Immediately Invoked Function Expression (IIFE) to protect the global scope and ensure the $ alias safely maps to jQuery.

(function ($) {
    $.fn.highlightText = function (options) {
        // 1. Define default options
        var defaults = {
            color: '#ffff00',
            fontWeight: 'bold',
            complete: null
        };

        // 2. Merge defaults with user-provided options
        var settings = $.extend({}, defaults, options);

        // 3. Iterate over the matched elements and apply settings
        return this.each(function () {
            $(this).css({
                backgroundColor: settings.color,
                fontWeight: settings.fontWeight
            });

            // Execute optional callback if provided
            if (typeof settings.complete === 'function') {
                settings.complete.call(this);
            }
        });
    };
}(jQuery));

Key Elements of the Pattern

  1. Accepting the Parameter: The plugin function accepts a single parameter, typically named options, which is expected to be a plain JavaScript object.
  2. Target Isolation: Using {} as the first argument in $.extend({}, defaults, options) creates a brand-new object. Without {}, defaults would be permanently altered by any passed options, causing side effects on future plugin calls.
  3. Chainability: Returning this.each(...) preserves jQuery's chaining capability, allowing developers to attach further jQuery methods directly to the call.

How to Use the Plugin

Users can now initialize the plugin with default settings or provide an object containing custom values.

// Using default settings
$('#intro').highlightText();

// Overriding specific options
$('#warning').highlightText({
    color: '#ff9999',
    complete: function () {
        console.log('Highlight applied.');
    }
});