Skip to content

Instantly share code, notes, and snippets.

@renanra
Created July 16, 2012 20:33
Show Gist options
  • Save renanra/3124870 to your computer and use it in GitHub Desktop.
Save renanra/3124870 to your computer and use it in GitHub Desktop.
jQuery Countable Plugin
;(function ( $, window, undefined ) {
var pluginName = 'countable',
document = window.document,
defaults = {
step: 1,
min: 1,
max: 0,
value: 1,
increase: ".increase",
decrease: ".decrease",
fn: function() {}
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
var that = this;
this.changeValue();
$(this.element).on("click", this.options.increase, function(e) {
that.changeValue("increase");
e.preventDefault();
});
$(this.element).on("click", this.options.decrease, function(e) {
that.changeValue("decrease");
e.preventDefault();
});
};
Plugin.prototype.changeValue = function(type) {
if (type == "increase") {
if (this.options.max == 0 || this.options.value + this.options.step <= this.options.max) {
this.options.value += this.options.step;
}
}
if (type == "decrease") {
if (this.options.min == 0 || this.options.value - this.options.step >= this.options.min) {
this.options.value -= this.options.step;
}
}
this.options.fn.call(this);
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
}
}(jQuery, window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment