Skip to content

Instantly share code, notes, and snippets.

@jasperf
Forked from publicJorn/jquery-plugin-template.js
Created November 19, 2021 08:47
Show Gist options
  • Save jasperf/9e641bbd6572fa0416e7fe5b32b9a8e6 to your computer and use it in GitHub Desktop.
Save jasperf/9e641bbd6572fa0416e7fe5b32b9a8e6 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));
}
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment