SyntaxStudy
Sign Up
jQuery jQuery Plugins — Summary
jQuery Intermediate 3 min read

jQuery Plugins — Summary

Plugins Summary

Key plugin patterns: extend $.fn, return this.each(), accept options with $.extend, namespace events, store instances with .data(), provide a destroy method.

Example
;(function($) {
  $.fn.myPlugin = function(options) {
    const defaults = { /* ... */ };
    const settings = $.extend({}, defaults, options);

    return this.each(function() {
      if ($(this).data("myPlugin")) return; // no double init

      const instance = { settings, el: this };
      $(this).data("myPlugin", instance);

      // Setup events with namespace
      $(this).on("click.myPlugin", handler);
    });
  };
}(jQuery));
Pro Tip

Save this template and use it as the starting point for every new jQuery plugin.