Making plugins with Jquery
by ne on 2021-09-29 under Javascript
Following is a simple jquery based plugin template
(function($) {
$.extend({ // adding our plugin to jquery
myPlugin: function(elem, command, args) {
// now iterate through the elements collection and do your operations, then return this, for chaining purpose.
return elem.each(function(index){
// do your operations here.
});
}
});
$.fn.extend({ // so that we can use $("body").myPlugin('operation1');
myPlugin: function(command) {
return $.myPlugin($(this), command, Array.prototype.slice.call(arguments, 1));
}
});
$.myPlugin.props = { // basic properties of our plugin
key1: "value1",
key2: "value2"
};
$.myPlugin.methods = { // functions related to plugin
fun1: function(param) {
/* do work */
},
fun2: function() {
/* do work */
}
};
})(jQuery);