SyntaxStudy
Sign Up
jQuery Plugin Destroy / Cleanup
jQuery Advanced 4 min read

Plugin Destroy / Cleanup

Destroy Method

A good plugin provides a destroy method that removes event listeners, cleans up DOM changes, and removes the data cache entry.

Example
$.fn.tooltip = function(method) {
  const methods = {
    init() {
      this.on("mouseenter.tooltip", showTip)
          .on("mouseleave.tooltip", hideTip);
    },
    destroy() {
      this.off(".tooltip")      // remove namespaced events
          .removeData("tooltip") // clear plugin data
          .find(".tip").remove(); // remove injected DOM
    }
  };
  return methods[method]
    ? methods[method].call(this)
    : methods.init.call(this);
};
Pro Tip

Use event namespaces (.tooltip) so you can remove only your plugin's events with .off(".tooltip").