Skip to content

Instantly share code, notes, and snippets.

@gosukiwi
Last active August 29, 2015 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gosukiwi/11274187 to your computer and use it in GitHub Desktop.
Save gosukiwi/11274187 to your computer and use it in GitHub Desktop.
jQuery plugin boilerplate
/*
* Minimal tooltip for jQuery by Federico Ramirez
*
* Usage: $('#myElement').myPlugin({});
* $('#myElement').myPlygin('myMethod', arg1, arg2);
* */
;(function ($, window, document, undefined) {
'use strict';
var pluginName = 'myPlugin',
defaults = {
myParam: 'myValue'
};
// The actual plugin constructor
function Plugin (element, options) {
this.$el = $(element);
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
// initialize your plugin
// return the element for chainability
return this.$el;
},
someMethod: function () {
// do something in the method
// return the element for chainability, if your method
// returns some value just remove this
return this.$el;
}
};
// Instantiation or method call, accordingly
$.fn[pluginName] = function (options) {
var args = Array.prototype.slice.call(arguments);
this.each(function() {
var instance = $.data(this, 'plugin_' + pluginName),
method;
if (!instance) {
$.data( this, 'plugin_' + pluginName, new Plugin(this, options));
} else {
method = args.shift();
return instance[method].apply(instance, args);
}
});
// chain jQuery functions
return this;
};
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment