jQuery Plugin
How to create a Full jQuery plugin
by Eiad Samman
HTML
Output in console
<div class="plugintest">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
JavaScript
(function ($) {
$.fn.myplugin = function (options) {
var settings = jQuery.extend({
param: 'value',
}, options);
var $jq = this;
var output = {
'get': function () {
$jq.each(function () {
var _this = this;
console.log("Reading param: " + _this._param);
});
return output;
},
'set': function (value) {
$jq.each(function () {
var _this = this;
console.log("Setting param: " + value);
_this._param = value;
});
return output;
},
'init': function () {
$jq.each(function () {
var _this = this;
_this.$this = $(this);
_this._param = "value";
var privatefunction = function () {
console.log("Calling: privatefunction();");
}
//Call private function on each jQuery element
privatefunction();
_this.$this.on('click', function (e) {
//jQuery events
});
});
output.set(settings.param);
}
}
output.init();
return output;
};
})(jQuery);
$(function () {
var myplugin = $(".plugintest > span").myplugin({
param: 100
});
myplugin.get().set(23).get();
});