jQuery Writing a Plugin
A jQuery plugin is a new method that you add to every jQuery object, so it can be used just like built-in methods: $(".price").formatCurrency(). Thousands of plugins (sliders, date pickers, validators) were written this way, and the pattern is still the cleanest way to package reusable jQuery code.
Where plugins live: $.fn
$.fn is jQuery's prototype — the object every jQuery collection inherits methods from. Anything you add to $.fn becomes available on all selections:
$.fn.makeRed = function () {
return this.css("color", "red"); // `this` is the jQuery object
};
$("p").makeRed();The rules of a good plugin
| Rule | Why |
|---|---|
Wrap it in (function ($) { … })(jQuery) |
Works even in noConflict mode, keeps helpers private |
Inside the method, this is already a jQuery object |
Do not wrap it again with $(this) at the top level |
Loop with this.each(…) when each element needs its own state |
One selection can contain many elements |
Return this (or the result of this.each) |
Keeps the plugin chainable |
Accept an options object merged with defaults |
Configurable without long argument lists |
Expose defaults as $.fn.pluginName.defaults |
Users can change them globally |
A first plugin: highlight
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
<p class="a">First paragraph</p>
<p class="b">Second paragraph</p>
<p class="c">Third paragraph</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
(function ($) {
$.fn.highlight = function (options) {
const settings = $.extend({}, $.fn.highlight.defaults, options);
return this.css({
backgroundColor: settings.background,
color: settings.color,
padding: "2px 6px",
borderRadius: "4px"
});
};
// public defaults that users can override globally
$.fn.highlight.defaults = { background: "#fff176", color: "inherit" };
})(jQuery);
$(".a").highlight(); // defaults
$(".b").highlight({ background: "#0769ad", color: "#fff" });
$.fn.highlight.defaults.background = "#c8f7c5"; // change globally
$(".c").highlight().append(" ✔"); // still chainable
console.log("plugin installed:", typeof $.fn.highlight);
</script>
</body>
</html>A plugin with per-element state
Real plugins usually attach behaviour and keep state per element. The pattern is return this.each(function () { … }), storing state with .data() so the plugin can tell whether it was already initialised.
This counter plugin turns any number input into a stepper with − and + buttons, and supports commands such as $(el).counter("value"):
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
.counter-wrap { display: inline-flex; gap: 4px; margin: 4px 0; }
.counter-wrap input { width: 50px; text-align: center; }
</style>
</head>
<body>
<label>Adults <input class="qty" value="2"></label><br>
<label>Children <input class="qty" value="0" data-max="4"></label><br>
<button id="read">Read values</button>
<button id="reset">Reset all</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
(function ($) {
const NAME = "counter";
const methods = {
init(options) {
return this.each(function () {
const $input = $(this);
if ($input.data(NAME)) return; // already initialised
const settings = $.extend({}, $.fn[NAME].defaults, options, $input.data());
const initial = Number($input.val()) || 0;
$input.data(NAME, { settings, initial });
const $minus = $("<button type='button'>−</button>");
const $plus = $("<button type='button'>+</button>");
$input.wrap("<span class='counter-wrap'></span>").before($minus).after($plus);
const set = v => {
v = Math.min(settings.max, Math.max(settings.min, v));
$input.val(v).trigger("counterchange", [v]); // custom event
};
$minus.on("click", () => set(Number($input.val()) - settings.step));
$plus.on("click", () => set(Number($input.val()) + settings.step));
});
},
value() {
return Number(this.first().val()); // getter: first element only
},
reset() {
return this.each(function () {
const state = $(this).data(NAME);
if (state) $(this).val(state.initial).trigger("counterchange", [state.initial]);
});
}
};
$.fn[NAME] = function (method, ...args) {
if (methods[method]) return methods[method].apply(this, args);
if (typeof method === "object" || !method) return methods.init.call(this, method);
$.error("Method " + method + " does not exist on jQuery." + NAME);
};
$.fn[NAME].defaults = { min: 0, max: 10, step: 1 };
})(jQuery);
// --- using the plugin ---
$(".qty").counter({ max: 6 })
.on("counterchange", function (e, value) {
console.log($(this).closest("label").contents().first().text().trim(), "→", value);
});
$("#read").on("click", function () {
$(".qty").each(function () { console.log("value:", $(this).counter("value")); });
});
$("#reset").on("click", () => $(".qty").counter("reset"));
</script>
</body>
</html>Things to notice:
$.extend({}, defaults, options, $input.data())— per-elementdata-max="4"overrides the call'smax: 6, which overrides the default10.- Calling
.counter()twice on the same input does nothing the second time, thanks to the.data(NAME)guard. - The plugin fires a custom event (
counterchange) with.trigger(name, [extraArgs]), so users can react without the plugin knowing about them. counter("value")is a getter, so it returns a number instead ofthis.
Adding utility functions
Not every plugin works on elements. Functions that operate on data go directly on $:
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
<ul id="prices"><li data-cents="1999"></li><li data-cents="250"></li><li data-cents="123456"></li></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
(function ($) {
// utility on $ (no elements involved)
$.formatMoney = function (cents, currency = "USD") {
return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(cents / 100);
};
// element method that uses the utility
$.fn.showMoney = function (currency) {
return this.text(function () {
return $.formatMoney($(this).data("cents"), currency);
});
};
})(jQuery);
console.log($.formatMoney(4250));
console.log($.formatMoney(4250, "EUR"));
$("#prices li").showMoney().css("font-weight", "bold");
</script>
</body>
</html>Plugin checklist
| ✔ | Item |
|---|---|
| ☐ | Wrapped in an IIFE that receives jQuery as $ |
| ☐ | Uses this.each for per-element work |
| ☐ | Returns this for chaining (getters excepted) |
| ☐ | Options merged with $.extend({}, defaults, options) |
| ☐ | Uses namespaced events (click.counter) and a destroy method in larger plugins |
| ☐ | Guards against double initialisation |
Tip: jQuery UI's widget factory (
$.widget("ns.name", {...})) implements all of this — options, methods, events, destroy — for you, if your project already loads jQuery UI.
Test yourself
Where do you attach a method so that all jQuery collections get it?
$.prototype$.fnwindow.jQuery.methods$.plugins
Why should a plugin method end with return this (or return this.each(...))?
- To free memory
- To keep the plugin chainable
- jQuery throws otherwise
- To run the plugin twice
Inside $.fn.myPlugin = function () { … }, what is this?
- A DOM element
- The jQuery object the plugin was called on
window$.fn