Skip to content

Instantly share code, notes, and snippets.

@mcwhittemore
Last active December 12, 2015 05:48
Show Gist options
  • Save mcwhittemore/4724591 to your computer and use it in GitHub Desktop.
Save mcwhittemore/4724591 to your computer and use it in GitHub Desktop.
Bootstrap jQuery plugin
;(function($, window, document, undefined) {
var namespace = "myPlugin";
var methods = {
init: function(options){}
}
$.fn[namespace] = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.'+namespace );
}
};
})(jQuery, window, document);
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="Example.js"></script>
</head>
<body>
<p>P1</p>
<p>P2</p>
<script>
$("p").myPlugin("logTextToConsole").myPlugin("changeTextTo", "hi").myPlugin("logTextToConsole");
</script>
</body>
</html>
;(function($, window, document, undefined) {
var namespace = "myPlugin";
var methods = {
init: function(options){},
logTextToConsole: function(){
return this.each(function(){
console.log($(this).text());
});
},
changeTextTo: function(text){
return this.each(function(){
$(this).text(text);
});
}
}
$.fn[namespace] = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.'+namespace );
}
};
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment