jQuery Plugin Development: Getting Started

By 
Zachary Watkins
Presented on 
.

Published on
;
 updated on
.

This presentation is an introduction to jQuery plugin development (using jQuery version 2.1.3). Slides are available. It was originally presented to developers at a meetup in College Station, Texas on July 12, 2015 from 11:00am to 11:30am CST. This was my first ever presentation to a group of developers and the slides are few but focused. I have not verified the code against later versions of jQuery.


Example Plugin

The example plugin is designed to parse the text content of an element into keys and values and attach the resulting JavaScript object to each element during runtime.

html
<div id="demo">
  <ol>
    <li>
      Customer A <br />
      <em>Joined - 2001</em> | <em>Last Rental - SUV</em> |
      <em>Purpose - Business</em>
    </li>
    <li>
      Customer B <br />
      <em>Joined - 2009</em> | <em>Last Rental - Hybrid</em> |
      <em>Purpose - Business</em> | <em>Current Customer - Yes</em>
    </li>
    <li>
      Customer C <br />
      <em>Joined - 2012</em> | <em>Last Rental - Minivan</em> |
      <em>Purpose - Personal</em>
    </li>
  </ol>
</div>
<script src="main.js" type="module"></script>
js
import(
  'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'
).then(() => {
  import('./jquery-plugin.js').then(() => {
    $('#demo ol li').gumboot({
      selector: 'em',
      separator: '-',
      callback: function (settings, index, length) {
        var $this = $(this);
        $this.append('<br>' + JSON.stringify($this.data('gumboot')));
      },
    });
  });
});
js
$.fn.gumboot = function (options) {
  var settings = $.extend(
    {
      selector: '.data',
      separator: ':',
    },
    $.fn.gumboot.defaults,
    options,
  );

  // Execute and return for chaining
  return this.each(function (index) {
    var data = {},
      $item = $(this);

    $item.find(settings.selector).each(function () {
      var pair = this.innerHTML.trim().split(settings.separator);
      data[pair[0].trim()] = pair[1].trim();
    });

    $item.data('gumboot', data);

    if ($.isFunction(settings.callback)) {
      settings.callback.call(this, settings, index, length);
    }
  });
};

Result:

  1. Customer A
    Joined - 2001 | Last Rental - SUV | Purpose - Business
  2. Customer B
    Joined - 2009 | Last Rental - Hybrid | Purpose - Business | Current Customer - Yes
  3. Customer C
    Joined - 2012 | Last Rental - Minivan | Purpose - Personal

Slides

2015-jquery-plugin-development.pdf

Further Reading