SyntaxStudy
Sign Up
jQuery Storing Plugin Instances with .data()
jQuery Advanced 4 min read

Storing Plugin Instances with .data()

Plugin Instance Storage

Store the plugin instance on each element using .data() to allow method calls after initialization and prevent double-initialization.

Example
$.fn.counter = function(options) {
  return this.each(function() {
    // Prevent double-init
    if ($(this).data("counter")) return;

    const instance = new Counter(this, options);
    $(this).data("counter", instance);
  });
};

// Later, access instance
$(".count-box").counter({ start: 0, end: 100 });
$(".count-box").data("counter").pause();
Pro Tip

Guard against double-initialization with an early return if data is already set.