jQuery timebomb plugin
Countdown and element content replacement
by Sergei Sokolov
HTML
<link rel="stylesheet" href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap.min.css">
<div id="timer-1"></div>
<div id="timer-2"></div>
CSS
#timer-1, #timer-2 {margin: 5px;padding:10px;border:1px solid #CCC}
JavaScript
// создание jQuery плагина
(function($){
var timebomb = function(){};
timebomb.prototype = {
defaults: {
time : 5, // по умолчанию время в секундах
countdown : '%COUNTDOWN% с. осталось',
prize : 'Ура!',
}
,init: function($el, opts) {
this.el = $el;
this.opts = $.extend({}, this.defaults, opts || {});
this.finish = (new Date).getTime() + 1000*this.opts.time;
this.update();
this.interval = window.setInterval( this.update.bind(this), 50);
}
,update: function() {
var toGo = Math.round( (this.finish - (new Date).getTime())/1000);
if( toGo > 0) this.el.html( this.opts.countdown.replace('%COUNTDOWN%', toGo));
else {
window.clearInterval( this.interval);
this.el.html( this.opts.prize);
}
}
};
$.fn.timebomb = function(opts) {
var tb = new timebomb();
tb.init(this, opts);
}
})( jQuery);
// применение
$('#timer-1').timebomb({
time: 6,
countdown: 'Ждите ещё %COUNTDOWN% секунд',
prize: '<button type="button" class="btn btn-success">Жми!</button>',
});
$('#timer-2').timebomb({time: 11});