jQuery · Integration

Plugins

Plugins add new methods to jQuery — date pickers, sliders, masks, validation. You will use many, and writing a small one teaches you how jQuery itself works.

Intermediate 5 min Lesson 17 of 22 Runnable examplesExamples use jQuery 3.x.
Before you start:Effects and Animations
0/22 in jQuery
On this page · 5 min · Intermediate

Learning objectives#

  • Load and initialise a third-party plugin
  • Pass options and call plugin methods
  • Write a plugin on $.fn with defaults
  • Keep plugins chainable

Explanation#

A plugin is a script that adds methods to $.fn, the prototype of every jQuery object. Load it after jQuery, then call $("#date").datepicker({ ... }).

Most plugins accept an options object merged with their defaults, and many expose methods: $("#slider").slick("slickNext").

To write one: $.fn.highlight = function (options) { const settings = $.extend({}, defaults, options); return this.each(function () { ... }); };

Return this (usually via this.each) so your plugin can be chained like built-in methods.

Popular examples: jQuery UI (datepicker, dialog), jQuery Validation, Select2, DataTables. Check that a plugin is maintained before adding it; many old ones are abandoned.

Syntax#

JavaScript Illustrative
$.fn.myPlugin = function (options) {
  const settings = $.extend({ color: 'yellow' }, options);
  return this.each(function () {
    $(this).css('background', settings.color);
  });
};
$('.note').myPlugin({ color: 'pink' }).fadeIn();

Code example: A character-counter plugin#

HTMLA character-counter plugin Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<div style="font-family:sans-serif">
  <p><textarea id="bio" rows="2" cols="40"></textarea></p>
  <p><input id="tweet" size="40"></p>
</div>
<script>
  (function ($) {
    $.fn.charCounter = function (options) {
      const settings = $.extend({ max: 100, warnAt: 0.9 }, options);


      return this.each(function () {
        const $field = $(this);
        const $label = $('<small>').insertAfter($field);


        function update() {
          const length = $field.val().length;
          $label.text(' ' + length + '/' + settings.max)
                .css('color', length > settings.max ? 'red' : length >= settings.max * settings.warnAt ? 'orange' : 'gray');
        }


        $field.on('input.charCounter', update);
        update();
      });
    };
  })(jQuery);


  $(function () {
    $('#bio').charCounter({ max: 160 });
    $('#tweet').charCounter({ max: 20 }).attr('placeholder', 'max 20 characters');
    console.log('Plugin installed:', typeof $.fn.charCounter);
  });
</script>
Expected output
Each field gets a grey counter (“0/160”, “0/20”) that updates as you type, turns orange near the limit and red above it. The console logs “Plugin installed: function”. The second call shows the plugin is chainable (.attr runs afterwards).
Opens this example in the full playground

Step-by-step explanation#

  1. The plugin is wrapped in (function ($) { ... })(jQuery) so $ is safe even if another library uses it.
  2. $.extend merges user options over the defaults.
  3. this.each runs the setup once per matched element and returns the jQuery object for chaining.
  4. A namespaced event (input.charCounter) makes it easy to remove later with .off(".charCounter").

Real-world use case#

An ASP.NET MVC admin uses DataTables for sortable, searchable tables and Select2 for searchable dropdowns — both jQuery plugins initialised in the view’s Scripts section.

Common mistakes#

“…is not a function”

The plugin script is missing, loaded before jQuery, or jQuery was loaded twice afterwards (wiping the plugin).

Not returning this

A plugin that returns nothing breaks chaining: $("x").myPlugin().hide() fails.

Abandoned plugins

Unmaintained plugins may have security bugs or break with jQuery 3. Prefer maintained ones or native solutions.

Best practices#

  • Load plugins after jQuery, once
  • Use $.extend for defaults
  • Return this.each(...)
  • Namespace events and data keys

Remember this#

Plugin = a new method on $.fn.

Options merged with $.extend(defaults, options).

return this.each(...) → chainable.

Practice exercise#

Your task: Write a plugin $.fn.uppercaseOnBlur() that converts an input’s value to upper case when it loses focus. Apply it to #pan.

Need a hint?
Inside this.each, bind .on("blur", ...) and set $(this).val($(this).val().toUpperCase()).
Show solution
HTML Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<input id="pan" value="abcde1234f">
<script>
  $.fn.uppercaseOnBlur = function () {
    return this.each(function () {
      $(this).on('blur', function () { $(this).val($(this).val().toUpperCase()); });
    });
  };
  $(function () { $('#pan').uppercaseOnBlur(); });
</script>
Opens this example in the full playground

Mini quiz#

Plugins quizMultiple choice Question 1 of 3

Where does a jQuery plugin add its method?

Score so far: 0/0

Want more? Practise all jQuery MCQs · jQuery interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.