Last active
August 29, 2015 14:11
-
-
Save sohooo/a2fcd0c6239e060b8498 to your computer and use it in GitHub Desktop.
jQuery plugin template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Protect the '$' alias and add scope by putting everything in | |
// an Immediately Invoked Function Expression: | |
// http://stage.learn.jquery.com/javascript-101/functions/#immediately-invoked-function-expression-iife | |
(function($) { | |
// As $.fn is just an alias for $.prototype, all jQuery | |
// objects ($ constructor) get our function. | |
$.fn.helloWorld = function(options) { | |
debug(this); | |
// Establish settings by merging the given options with the plugin defaults. | |
var settings = $.extend({}, $.fn.helloWorld.defaults, options); | |
// Return 'this' so this plugin is chainable. | |
return this.each(function() { | |
//$(this).text(settings.text); | |
$(this).html($.fn.helloWorld.format(settings.text)); | |
if (settings.color) { | |
$(this).css('color', settings.color); | |
} | |
if (settings.fontStyle) { | |
$(this).css('font-style', settings.fontStyle); | |
} | |
if ($.isFunction(settings.complete)) { | |
settings.complete.call(this); | |
} | |
}); | |
// Private function for debugging, which is only accessible inside | |
// this plugin. This minimizes the plugin footprint/surface/API. | |
function debug( obj ) { | |
if ( window.console && window.console.log ) { | |
window.console.log( "helloWorld selection count: " + obj.length ); | |
} | |
}; | |
}; | |
// Provide access to default plugin settings. | |
// Usage: $.fn.helloWorld.defaults.text = '¡Hola, mundo!'; | |
$.fn.helloWorld.defaults = { | |
text: 'Hello World!', | |
color: null, | |
fontStyle: null, | |
complete: null | |
}; | |
// Public access to secondary function 'format'. This allows for | |
// easy customization of the formatter. | |
$.fn.helloWorld.format = function( txt ) { | |
return "<strong>" + txt + "</strong>"; | |
}; | |
}(jQuery)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
$(document).ready(function() { | |
$.fn.helloWorld.defaults.text = '¡Hola, mundo!'; | |
$('h1').helloWorld({ | |
color: '#005dff', | |
fontStyle: 'italic' | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment