Three Ways to Configure a jQuery Plugin

Demo that shows how you can configure a jQuery plugin with defaults, option parameters or data attributes

by Patrick Hund

HTML

<h1>Three Ways to Configure a jQuery Plugin</h1>

<ul>
    <li id="blue">This list item gets config setting "color: blue" from the defaults, because no option "color" is specified</li>
    <li id="green">This list item gets config setting "color: green" from the options passed to the jQuery plugin when it is initialized (option parameter overrides default)</li>
    <li id="red" data-color="red">This list item gets config setting "color: red" from a data attribute of the element on which the jQuery plugin is initialized (data attribute overrides default)</li>
    <li id="orange" data-color="hotpink">This list item gets config setting "color: orange" from the options passed to the jQuery plugin, the data attribute is ignored (option parameter overrides data attribute)</li>
</ul>

JavaScript

// the plugin functionality
function colorMe(element, options) {
    var $element = $(element),
        defaults,
        settings;

    function setOptionFromData(key) {
        if ($element.data(key) !== undefined && options[key] === undefined) {
            options[key] = $element.data(key);
        }
    }

    if (options === undefined) {
        options = {};
    }

    defaults = {
        color: "blue"
    };

    $.each(defaults, setOptionFromData);

    settings = $.extend(true, defaults, options);

    $element.css("color", settings.color);
}

// jQuery plugin initialization
$.fn.colorMe = function (options) {
    return this.each(function () {
        colorMe(this, options);
    });
};

// attaching the plugin to the DOM
$("#blue").colorMe();
$("#green").colorMe({
    color: "green"
});
$("#red").colorMe();
$("#orange").colorMe({
    color: "orange"
});