Plugins

Harry · 11 Sep 2026 · 10 views

Extending jQuery

A plugin adds a method to jQuery.fn (the prototype of all jQuery objects), so every element selection can call it.

A Minimal Plugin

(function ($) {
  $.fn.highlight = function (color) {
    this.css('background-color', color);
    return this;               // keep the chain working
  };
})(jQuery);

$('p').highlight('#ffe57f');

The (function ($) { ... })(jQuery) wrapper protects against conflicts and keeps jQuery in scope.

Options With Defaults

(function ($) {
  $.fn.tooltip = function (opts) {
    var settings = $.extend({ text: 'Info', delay: 300 }, opts);
    return this.each(function () {
      $(this).attr('title', settings.text);
    });
  };
})(jQuery);

$('[data-tip]').tooltip({ text: 'Helpful tip' });

$.extend merges user options over defaults. Returning this.each() returns the collection so plugin calls chain.

Avoiding Name Collisions

  • Prefix plugin names, e.g. ck. or gg. namespace.
  • Never pollute $ directly; attach to $.fn.
  • Wrap in an IIFE to keep internals private.

Key Points

  • Plugins are methods on $.fn, returning this for chaining.
  • $.extend handles default options cleanly.
  • IIFE wrappers avoid global pollution and $ conflicts.
  • Prefix names to play nicely with other plugins.
Share this post:

Comments (0)

Please login or register to comment.