Heads up! This post was written 13 years ago. Some information might be outdated or may have changed since then.
(function($) {
$.countdwn = function(element, options) {
var defaults = {
time_end : '',
onStart : function(){}
};
var plugin = this;
plugin.settings = {};
var $element = $(element);
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
start_count();
plugin.settings.onStart();
};
var count = function() {
now = Math.round((new Date()).getTime() / 1000);
seconds = dateDiff(now, plugin.settings.time_end / 1000);
seconds.h = seconds.h + (seconds.d * 24);
hours = str_pad(seconds.h, 2, '0', 'STR_PAD_LEFT').split("");
min = str_pad(seconds.m, 2, '0', 'STR_PAD_LEFT').split("");
scn = str_pad(seconds.s, 2, '0', 'STR_PAD_LEFT').split("");
$element.find('.hours_dash').find('.digit:eq(0)').html(hours[0]);
$element.find('.hours_dash').find('.digit:eq(1)').html(hours[1]);
$element.find('.minutes_dash').find('.digit:eq(0)').html(min[0]);
$element.find('.minutes_dash').find('.digit:eq(1)').html(min[1]);
$element.find('.seconds_dash').find('.digit:eq(0)').html(scn[0]);
$element.find('.seconds_dash').find('.digit:eq(1)').html(scn[1]);
start_count();
};
var dateDiff = function( str1, str2 ) {
str2 = str2 * 1000;
str1 = str1 * 1000;
var diff = str2 - str1;
return isNaN( diff ) ? NaN : {
diff : diff,
ms : Math.floor( diff % 1000 ),
s : Math.floor( diff / 1000 % 60 ),
m : Math.floor( diff / 60000 % 60 ),
h : Math.floor( diff / 3600000 % 24 ),
d : Math.floor( diff / 86400000 )
};
};
var start_count = function() {
setTimeout(function(){ count(); }, 1000);
};
var str_pad = function(input, pad_length, pad_string, pad_type) {
var half = '',pad_to_go;
var str_pad_repeater = function (s, len) {
var collect = '';
while (collect.length < len) {
collect += s;
}
collect = collect.substr(0, len);
return collect;
};
input += '';
pad_string = pad_string !== undefined ? pad_string : ' ';
if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') {
pad_type = 'STR_PAD_RIGHT';
}
if ((pad_to_go = pad_length - input.length) > 0) {
if (pad_type == 'STR_PAD_LEFT') {
input = str_pad_repeater(pad_string, pad_to_go) + input;
} else if (pad_type == 'STR_PAD_RIGHT') {
input = input + str_pad_repeater(pad_string, pad_to_go);
} else if (pad_type == 'STR_PAD_BOTH') {
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
input = half + input + half;
input = input.substr(0, pad_length);
}
}
return input;
};
plugin.init();
};
$.fn.countdwn = function(options) {
return this.each(function() {
if (undefined == $(this).data('countdwn')) {
var plugin = new $.countdwn(this, options);
$(this).data('countdwn', plugin);
}
});
};
})(jQuery); html частта може да изглежда по следния начин:
а използването на плъгина да става така var ts = 1345064399 * 1000;
$('#timerche').countdwn({
time_end: ts
});