SyntaxStudy
Sign Up
jQuery Plugin Options with $.extend
jQuery Intermediate 4 min read

Plugin Options with $.extend

Plugin Options

Accept an options object and merge it with defaults using $.extend(). This gives users flexibility while keeping sensible defaults.

Example
$.fn.popupAlert = function(options) {
  const settings = $.extend({
    message: "Hello!",
    delay:   2000,
    color:   "green"
  }, options);

  return this.each(function() {
    const el = $(this);
    el.text(settings.message).css("color", settings.color).show();
    setTimeout(() => el.hide(), settings.delay);
  });
};

// Override specific options
$(".notice").popupAlert({ message: "Saved!", delay: 3000 });
Pro Tip

$.extend({}, defaults, options) creates a new object, preventing mutation of defaults.