Skip to content

Instantly share code, notes, and snippets.

@dmgig
Last active April 4, 2017 20:13
Show Gist options
  • Save dmgig/99088b8a12837986f40b6ba115dd77b4 to your computer and use it in GitHub Desktop.
Save dmgig/99088b8a12837986f40b6ba115dd77b4 to your computer and use it in GitHub Desktop.
jQuery Plugin Boilerplate
/* Fiddle: https://jsfiddle.net/dmgig/1rhetrhb/ */
(function ( $ ) {
var Plugin = function(el){
var plugin = {};
var config = {
backgroundColor: 'blue'
}
plugin.el = el;
var $el = $(el);
var $elSpan;
plugin.methods = {
init: function(options){
$elSpan = $el.find('span');
$.extend(config, options);
$el.css(config);
},
makeDoThing: function(size){
$el.css({ fontSize: size+'px' });
$elSpan.html('HELLO');
}
}
return plugin;
}
var INSTANCES = {};
$.fn.testPlugin = function(input){
var EL = this;
var ARGS = arguments;
this.each(function(){
var id = $(this).attr('id');
if(!INSTANCES[id]){
INSTANCES[id] = new Plugin(EL);
}
var plugin = INSTANCES[id];
if ( plugin.methods[input] ) {
return plugin.methods[input].apply( plugin.el, Array.prototype.slice.call( ARGS, 1 ));
} else if ( typeof input === 'object' || !input ) {
plugin.methods.init(input);
} else {
$.error( 'Method ' + input + ' does not exist on jQuery.narratorsGrid' );
}
});
}
}(jQuery));
$('#me').testPlugin();
$('#metoo').testPlugin({ backgroundColor: 'red' });
$('#methree').testPlugin({ backgroundColor: 'yellow' });
$("#me").testPlugin('makeDoThing', 35);
$("#metoo").testPlugin('makeDoThing', 50);
/* HTML
<div id="me">
ME
<span></span>
</div>
<div id="metoo">
ME TOO
<span></span>
</div>
<div id="methree">
ME THREE
<span></span>
</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment