How to ...
$('a').css('color', 'red');
$
means to return a jquery object$.fn
object$.fn
object!
$.fn.pluginName = function() {};
$("a").pluginName();
$.fn
, control functions with if
statements.return this
return this.each(function() {})
mkdir jquery_plugin
cd jquery_plugin && mkdir css && mkdir js && mkdir images && touch index.html
jquery-1.9.1.min.js
[here](https://gist.githubusercontent.com/jinthagerman/5
187dfae5bce5c6f208a/raw/176a5d0fc2ea6b7c6db0deb238d657844e292a27/jquery-1.9.1.min.js)js/jquery-1.9.1.min.js
touch js/jquery.hello-world.js
index.html
add the source to load your js files at the bottom of the html page just before
the closing body tag :<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery-hello-world.js"></script>
(function($) {
$.fn.helloWorld = function() {
// contains js code
return this.each(function() {
$(this).text("Hello World!");
}
}
}(jQuery));
$.fn
is jQuery's way of allowing you to define your own plugin, in this case is named
helloWorld
helloWorld
function will executethis
will refer to
the actual jquery object, and once you iterate through the object, you will need to refer to it
by using $(this)
.$(document).ready(function() {
$("div").helloWorld();
)};
(function($) {
$.fn.helloWorld = function(arg1) {
return this.each(function() {
$(this).text(arg1)
});
}
}(jQuery));
// Call it in the script files as ...
$().helloWorld("Whatever");
(function($) {
$.fn.helloWorld = function(options) {
// ESTABLISH SETTINGS
var settings = $.extend({
text: 'Hello WORLD!',
color: null,
fontStyle: null
}, options);
return this.each(function() {
$(this).text(settings.text)
});
}
}(jQuery));
$().helloWorld({text: "Hi!"})
// Need to pass the text arg as an object
// Save your defaults in a variable to prevent them from being over-written
(function($) {
$.fn.helloWorld = function(options) {
// ESTABLISH SETTINGS in a variable
var defaults = {
text: 'Hello WORLD!',
color: null,
fontStyle: null,
callbackName: function() {}
}
var settings = $.extend({}, defaults, options);
return this.each(function() {
$(this).text(settings.text)
});
}
}(jQuery));
settings
object has been declared, so that when the plugin is invoked devoid of any args
, it will use the default text due to $.extend({})
// in the settings object:
var settings = $.extend({
text: "Hello!",
complete: null
}, options);
complete
is a function that will be executed once the helloWorld
plugin runs$.fn.isFunction
return this.each(function() {
if($.isFunction(settings.complete)) {
settings.complete.call(this);
}
});
//...
// To invoke a function
$().helloWorld({
text: "Hello",
complete: function() {
alert("Plugin Activated!");
}
});
(function($) {
// PUBLIC METHODS
// Need an initialize method
this.initialize = function() {
return this;
}
// Add your methods here
this.methodName = function(args) {
// stuffs in here
}
return this.intialize();
}(jQuery));