jQuery Plugins

A jQuery plugin is a new method which you add to jQuery, so you can use it on any selection, like the built in methods. There are thousands of ready plugins (sliders, date pickers, lightboxes), and you can write your own.

Use a plugin

  1. Load jQuery first.
  2. Load the plugin file after it.
  3. Call the plugin method on your elements, usually in the ready function.
<script src="jquery-3.7.1.min.js"></script>
<script src="jquery.myplugin.js"></script>
<script>
  $(function () {
    $('.gallery').myPlugin({ speed: 300 });
  });
</script>

Before you use a plugin, check that it is maintained and works with your jQuery version. Many old plugins are not updated and can break in jQuery 4.

Create a simple plugin

Plugin methods are added to $.fn. Inside the method, this is the jQuery object of the selected elements.

<p class="note">One</p>
<p class="note">Two</p>
<p>Three</p>
$.fn.highlight = function () {
  return this.css('background-color', 'yellow');
};

$('.note').highlight();
HTML after the code runs

<p class="note" style="background-color: yellow;">One</p>
<p class="note" style="background-color: yellow;">Two</p>
<p>Three</p>

The line return this (here with this.css(...) which returns the same object) keeps chaining possible.

Plugin with options

Give your plugin default options and let the user change them with $.extend().

$.fn.highlight = function (options) {
  var settings = $.extend({
    color: 'yellow',
    bold: false
  }, options);

  return this.each(function () {
    $(this).css('background-color', settings.color);
    if (settings.bold) {
      $(this).css('font-weight', 'bold');
    }
  });
};

$('.note').first().highlight();
$('.note').last().highlight({ color: 'lightgreen', bold: true }).addClass('done');
HTML after the code runs

<p class="note" style="background-color: yellow;">One</p>
<p class="note done" style="background-color: lightgreen; font-weight: bold;">Two</p>
<p>Three</p>

  • this.each() makes sure the plugin works for every element of the selection.
  • The return makes it possible to chain: .highlight().addClass('done').
  • Defaults and user options are merged in a new object, so the defaults are not changed.

Safe wrapper for the $ sign

Write your plugin inside an immediately invoked function, so it works even if $ is used by another library.

(function ($) {

  $.fn.highlight = function (options) {
    var settings = $.extend({ color: 'yellow' }, options);
    return this.css('background-color', settings.color);
  };

})(jQuery);

Plugin with an action (method)

<div id="counter">0</div>
(function ($) {
  $.fn.counter = function (action) {
    return this.each(function () {
      var $el = $(this);
      var n = parseInt($el.text(), 10);

      if (action === 'increase') n++;
      if (action === 'reset') n = 0;

      $el.text(n);
    });
  };
})(jQuery);

$('#counter').counter('increase').counter('increase').counter('increase');
console.log($('#counter').text());
$('#counter').counter('reset');
console.log($('#counter').text());
Console output

3
0

Tips for good plugins

  • Use a clear and unique method name, to not clash with other plugins.
  • Always return this (or the result of each) to keep chaining.
  • Do not make global variables.
  • Give default options and write the options in a document.
  • Name the file jquery.pluginname.js.
Note: Writing a small plugin is a good way to organize your own repeated code. Next: Deferred and Promises.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.