Skip to content

Instantly share code, notes, and snippets.

@publicJorn
Last active November 19, 2021 08:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save publicJorn/94bff6836ad1fc2ada8a to your computer and use it in GitHub Desktop.
Save publicJorn/94bff6836ad1fc2ada8a to your computer and use it in GitHub Desktop.
jQuery plugin template
/**
* jQuery plugin template by https://github.com/publicJorn
* Features:
* - dynamic plugin name (only supply once) so it's easy to change later
* - plugin factory to make it work in the browser, or with AMD / COMMONJS modules
* - Plugin instance is saved on the selector element
* - Default options are saved to the instance in case you need to figure out a difference between passed options
*/
(function(global, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], function($) {
return factory($, global, global.document);
});
} else if (typeof exports === "object" && exports) {
module.exports = factory(require('jquery'), global, global.document);
} else {
factory(jQuery, global, global.document);
}
})(typeof window !== 'undefined' ? window : this, function($, window, document, undefined) {
'use strict';
// -- Name is used to keep jQUery plugin template portable
var pluginName = 'pluginName';
// -- Globals (shared across all plugin instances)
var defaultOptions = {};
var $window = $(window);
var $document = $(document);
// -- Plugin constructor
// Using p object as placeholder, together with pluginName to make jQuery plugin template portable
var p = {}; p[pluginName] = function (el, options) {
this.el = el;
this.options = $.extend({}, defaultOptions, options) ;
this._defaultOptions = defaultOptions;
this.init();
}
// Rest of the functions
p[pluginName].prototype = {
/**
*
*/
init: function() {
console.info('initialised');
}
};
// -- Prevent multiple instantiations
$.fn[pluginName] = function(options) {
return this.each(function () {
if (!$.data(this, 'plugin_'+ pluginName)) {
$.data(this, 'plugin_'+ pluginName, new p[pluginName](this, options));
}
});
};
});
@publicJorn
Copy link
Author

If you are interested, there's also an ES6 version
Note that it requires a build step to transpile to ES5 if you intend to use it directly in the browser. Use webpack or browserify for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment