Skip to content

Instantly share code, notes, and snippets.

@seethroughdev
Created March 15, 2012 19:03
Show Gist options
  • Save seethroughdev/2046085 to your computer and use it in GitHub Desktop.
Save seethroughdev/2046085 to your computer and use it in GitHub Desktop.
Testing Custom Countdown plugin
(function($){
$.fn.wedgeCountdown = function(options) {
//set default options
var defaults = {
date : null,
showSeconds : true,
complete : null,
completeText: "Timer done!"
};
// call options/defaults
options = $.extend(defaults, options);
return this.each(function(){
var $this = $(this);
var interval, countDownTime;
function convertDateToUtc(convertedDate) {
convertedDate = new Date(convertedDate);
// get timezone offset in seconds
var utcOffset = convertedDate.getTimezoneOffset() * 60;
// get countdown date
convertedDate = Date.parse(convertedDate) / 1000;
// calculate final countDownDate with offset
convertedDate = convertedDate + utcOffset;
return convertedDate;
}
function countDown() {
// get countdown date and convert to UTC
var countDownDate = $this.attr('datetime');
countDownDate = convertDateToUtc(countDownDate);
// get current date and convert to UTC
var currentDate = Math.floor($.now());
currentDate = convertDateToUtc(currentDate);
// get difference
var seconds = countDownDate - currentDate;
// find out all days, minutes, seconds
var days = Math.floor(seconds / (60 * 60 * 24));
seconds -= days * 60 *60 * 24;
var hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60;
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
// add 0 to number if less than 10 for spacing
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
// create counter var
if (days > 0) {
countDownTime = days + 'd ' + hours + 'h ' + minutes + 'm ';
} else {
countDownTime = hours + 'h ' + minutes + 'm ';
}
// show seconds unless option is false
if (options.showSeconds === true) {
countDownTime = countDownTime + ' ' + seconds + 's';
}
// when countDownDate is past
if (countDownDate <= currentDate) {
clearInterval(interval);
countDownTime = options.completeText;
// if exists, run complete callback
if (options.complete !== null) {
options.complete();
}
}
// replace element with countdown length
$this.text(countDownTime);
}
var intervalRate = 1000;
// check timer every second
interval = setInterval(countDown, intervalRate);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment