Плагин таймера
by Евгений
HTML
<div class="sad_action">
<h3><a href="http://www.rassada.net/shop/gorjachie-predlozhenija">Акция "Солнечный август 2014"</a></h3>
<div class="action_time" data-date="2014-10-01"></div>
</div>
<div class="sad_action">
<h3><a href="http://www.rassada.net/shop/gorjachie-predlozhenija">Акция "Солнечный август 2014"</a></h3>
<div class="action_time" data-date="2014-08-01"></div>
</div>
JavaScript
;(function( $ ){
// функция для склонения слов (значение, (1)"день", (2)"дня", (5)"дней")
function plural(n,str1,str2,str5){return n + ' ' + ((((n%10)==1)&&((n%100)!=11))?(str1):(((((n%10)>=2)&&((n%10)<=4))&&(((n%100)<10)||((n%100)>=20)))?(str2):(str5)))}
function humanTime (str) {return str < 10 ? '0' + str : str}
function updateTimer(el, end) {
if(end instanceof Date) {
var html,
last,
now = new Date(),
lastSec = Math.floor( ( end.getTime() - now.getTime() ) / 1000 );
if (lastSec < 0 ) {
$(el).html('Акция закончена.');
} else {
last = {
seconds : lastSec % 60,
minutes : Math.floor(lastSec / 60) % 60,
hours : Math.floor(lastSec / 60 / 60) % 24,
days : Math.floor(lastSec / 60 / 60 / 24)
};
html = 'До конца акции осталось ';
html += plural(last.days, 'день', 'дня', 'дней');
html += ' и ' + humanTime(last.hours) + ':' + humanTime(last.minutes) + ':' + humanTime(last.seconds);
$(el).html(html);
setTimeout(function() {
updateTimer(el, end);
}, 1000)
}
}
}
$.fn.actionTimer = function() {
return this.each(function() {
var end,
already = $(this).data('initialed'),
dateToParse = $(this).data('date');
if (already === undefined && dateToParse !== undefined) {
if (dateToParse.match(/[0-9]{4}([\/\-][0-9]{1,2}){2}( [0-9]{1,2}(:[0-9]{2}){2})?/)) {
dateToParse = dateToParse.replace(/\-/g, '/');
end = new Date(dateToParse);
updateTimer(this, end);
$(this).data('initialed', 1);
}
...