Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 56 ยท Plugins and Utilities

Writing Your Own Plugin

Write your own jQuery plugin with $.fn: keep chaining by returning this, merge default options, store per-element state with .data(), add methods and clean up namespaced events.

A jQuery plugin is just a function attached to $.fn, the prototype of every jQuery object. Once it exists, you call it like any built-in method: $("input").charCounter(). Plugins let you package behaviour you use more than once (a counter, a tooltip, a tab widget) so the page only says what it wants and the plugin handles how.

Writing a good plugin is mostly discipline: return this so chaining keeps working, accept options with sensible defaults, remember state per element, and clean up after yourself. This lesson builds up those habits step by step. You need to know implicit iteration, $.extend and .data().

Anatomy of a good plugin

$.fn.name The function becomes a jQuery method.
Return this Keeps chaining alive.
Options Defaults merged with $.extend.
State Stored per element with .data().
1 / 2

The smallest plugin

Inside $.fn functions, this is the jQuery object the method was called on, not a DOM element. So you can use jQuery methods on this directly. To act on each element separately, call this.each() and, inside, this is a single DOM element.

JavaScript
$.fn.zebra = function () {
  return this.each(function () {
    $(this).children(":odd").css("background", "#f1f5f9");
  });
};

$("ul").zebra();

Two rules are visible even here. First, the function returns this.each(...), and .each() returns the same collection, so $("ul").zebra().addClass("striped") still works. Second, the plugin works on every element in the collection, not only the first one, which is what users expect from jQuery.

Wrap the code and protect $

Your plugin file will be loaded on pages that might use other libraries which also define $. Wrap the code in an immediately invoked function expression and receive jQuery as the parameter named $. Inside the wrapper $ always means jQuery, even after someone calls $.noConflict(). The wrapper also keeps your helper variables out of the global scope.

JavaScript
(function ($) {
  $.fn.zebra = function () {
    return this.each(function () {
      $(this).children(":odd").addClass("zebra-row");
    });
  };
})(jQuery);

Options with defaults

Users should be able to customise a plugin without editing it. Define a defaults object, expose it as a property of the plugin so people can change the defaults globally, and merge the per-call options over it with $.extend using an empty first argument so the defaults stay untouched.

JavaScript
(function ($) {
  $.fn.zebra = function (options) {
    var settings = $.extend({}, $.fn.zebra.defaults, options);

    return this.each(function () {
      $(this).children(":odd").css("background", settings.color);
    });
  };

  $.fn.zebra.defaults = { color: "#f1f5f9" };
})(jQuery);

Now $("ul").zebra() uses the default colour, $("ul").zebra({ color: "gold" }) overrides it for that call, and $.fn.zebra.defaults.color = "pink" changes the default for everyone.

A first plugin with options and chaining

Per-element state with .data()

A plugin that adds behaviour to elements needs to remember things about each one: its settings, a timer, a counter. Store them with .data() under a key named after the plugin. That has two benefits. State belongs to the element, so two elements never interfere, and calling the plugin a second time on the same element can find the existing state and avoid initialising twice.

JavaScript
var state = $(this).data("zebra");
if (state) { return; }   // already set up
$(this).data("zebra", { settings: settings });

Never keep per-element state in a single variable inside the plugin closure. That variable would be shared by every element the plugin touches.

The methods pattern

Many plugins expose more than one action: set up, refresh, read a value, tear down. The convention is that the first argument is either an options object (initialise) or a method name string:

JavaScript
$("#note").charCounter({ max: 80 });   // initialise
$("#note").charCounter("update");      // call a method
$("#note").charCounter("destroy");     // clean up

Implement it with a table of methods and a small dispatcher. Unknown names should raise a clear error through $.error().

Namespaces and cleanup

A plugin that binds events must also be able to remove them, and it must not remove events that belong to someone else. Namespaced events solve this: bind "input.charCounter" and later call .off(".charCounter"), which removes only your handlers. Also remove any elements the plugin created, and delete the stored data. A destroy method that restores the original state is the sign of a polished plugin.

A character counter plugin with methods and destroy

Press Destroy, then Init again: nothing is duplicated, because destroy removed the label and the namespaced handler, and init checks for existing state.

Publishing and good habits

  • Name it carefully. Check that $.fn.yourName does not collide with an existing method; the name should be specific.
  • Do not hard-code selectors. A plugin should work on whatever element it receives.
  • Expose defaults and callbacks (onChange, onOpen) and trigger custom events with .trigger() so page code can react (see custom events).
  • Prefer classes to inline styles, so users can restyle with CSS.
  • Add accessibility from the start: roles, labels and keyboard support, as the tabs and accordion project shows.
  • Keep it small. If a plugin only wraps one line of native code, you probably do not need a plugin.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a plugin function normally end with return this.each(...)?

    Returning the jQuery object preserves chaining, and .each() makes the plugin work on every matched element, not just the first.
  2. 2. Inside a $.fn plugin function, outside of .each(), what is this?

    this is already a jQuery object, so you can call jQuery methods on it directly. Inside the .each() callback it becomes a single DOM element.
  3. 3. Why wrap the plugin in (function ($) { ... })(jQuery)?

    The IIFE receives jQuery as $, so the plugin still works after $.noConflict() and its helper variables do not leak into the global scope.
  4. 4. What is the benefit of binding events as "input.charCounter"?

    A namespace labels your handlers so cleanup does not remove handlers that belong to other code.
  5. 5. Where should a plugin keep the settings for each element?

    A shared variable would be overwritten by the next element. .data() ties the state to the element it belongs to.

Summary

  • A plugin is a function on $.fn; this is the jQuery object, and this.each() gives you each DOM element.
  • Return this (usually return this.each(...)) to preserve chaining.
  • Wrap the code in (function ($) { ... })(jQuery) and expose defaults as $.fn.name.defaults; merge with $.extend({}, defaults, options).
  • Store state per element with .data(), guard against double initialisation, and dispatch method names such as update and destroy.
  • Namespace your events, and make destroy remove handlers, created elements and stored data.

Next, see how to choose, load and use plugins written by others in Using Plugins and jQuery UI.