I’m new to Jquery plugin creation. Following jquery plugin is created using jQuery Boilerplate. It just do a count-up and notify when count-up finished.
I want to have a function to restart count-up by setting counter to 0;
I dont understand how to call that reset function
;(function ( $, window, undefined ) {
var pluginName = 'countup',
document = window.document,
defaults = {
countSince: new Date(),
countUpTo:120,
notifyAfter:110,
onExpire:function() {
},
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {counter:0}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
this.tick();
};
Plugin.prototype.reset = function () {
this.options.counter = 0;
};
Plugin.prototype.tick = function () {
if (this.options.counter > this.options.countUpTo) {
//timer expired
this.options.onExpire($(this.element));
}
else {
if (this.options.counter > this.options.notifyAfter) {
$(this.element).find('span').html('<strong style="font-size: 15px; color:#ff0000;">' + this.options.counter+ ' seconds</strong>');
}
else {
$(this.element).find('span').html('<strong style="font-size: 15px; color:#3366ff">' + this.options.counter + ' seconds</strong>');
}
setTimeout(function() {
this.options.counter += 1;
this.tick();
}, 1000);//calling tick function again
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
};
}(jQuery, window));
on document ready ::
$('#countdown').countup({
onExpire:function() {
alert('hi');
},
countSince:new Date(),//count from this
countUpTo:30,//seconds from the countSince to expire
notifyAfter:20
})
after that i want to call reset() function on $(‘#countdown’). how to do that? Or is there a better way to write above code? Please give me some help here.
The boiler-plate code you created is awfully complicated. The following HTML and JavaScript (along with jQuery) will accomplish an upward counter from 0 until a number of seconds defined by
var countToat which point it will print the message stored invar successMsg. The reset button restarts the counter at zero.HTML:
JavaScript:
I’ve put the solution up on jsFiddle: http://jsfiddle.net/TxVnS/2/
Update:
A solution to allow for variable counter ids is here: http://jsfiddle.net/TxVnS/6/