SyntaxStudy
Sign Up
jQuery Writing jQuery Plugins
jQuery Advanced 12 min read

Writing jQuery Plugins

Writing jQuery Plugins

jQuery plugins extend $.fn to add custom methods to the jQuery object.

Basic Plugin Structure

;(function($) {
    $.fn.highlight = function(options) {
        var settings = $.extend({
            color: "yellow",
            duration: 400
        }, options);

        return this.each(function() {
            $(this)
                .css("background-color", settings.color)
                .delay(settings.duration)
                .queue(function(next) {
                    $(this).css("background-color", "");
                    next();
                });
        });
    };
}(jQuery));

Using the Plugin

$("p").highlight();
$("h2").highlight({color: "lightblue", duration: 800});

// Chainable
$("p").highlight().addClass("done");
Pro Tip

Always return this (or this.each()) from plugins to maintain jQuery chainability.