Last active
March 20, 2017 02:11
-
-
Save alexsasharegan/fba8202b4ce88c9eaa89cc114d3be222 to your computer and use it in GitHub Desktop.
Javascript to animate a countdown. Ideal for a coming soon or event page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( function ( ) { | |
'use strict'; | |
function Countdown( endDate, elSelector ) { | |
if ( endDate instanceof Date ) { | |
this.countdownDate = endDate.getTime( ); | |
} else { | |
this.countdownDate = new Date( endDate ).getTime( ); | |
} | |
var selector = elSelector || Countdown.DEFAULTS.selector; | |
this.element = document.querySelector( selector ); | |
this.intervalId = null; | |
this.countdown = this.countdown.bind( this ); | |
} | |
Countdown.SECOND = 1000; | |
Countdown.MINUTE = 60 * Countdown.SECOND; | |
Countdown.HOUR = 60 * Countdown.MINUTE; | |
Countdown.DAY = 24 * Countdown.HOUR; | |
Countdown.DEFAULTS = { | |
selector: '#countdown-display', | |
doneText: "EXPIRED" | |
}; | |
Countdown.prototype.countdown = function ( ) { | |
// Get today's date and time | |
var now = new Date( ).getTime( ); | |
// Find the distance between now an the count down date in ms | |
var distance = this.countdownDate - now; | |
// Time calculations for days, hours, minutes and seconds | |
var days = Math.floor( distance / Countdown.DAY ) + 'd'; | |
var hours = Math.floor( ( distance % Countdown.DAY ) / Countdown.HOUR ) + 'h'; | |
var minutes = Math.floor( ( distance % Countdown.HOUR ) / Countdown.MINUTE ) + 'm'; | |
var seconds = Math.floor( ( distance % Countdown.MINUTE ) / Countdown.SECOND ) + 's'; | |
// Display the result | |
this.element.innerHTML = [ days, hours, minutes, seconds ].join( ' ' ); | |
// If the count down is finished, write the done text | |
if ( distance < 0 ) { | |
this.stop( ); | |
this.element.innerHTML = Countdown.DEFAULTS.doneText; | |
} | |
return this; | |
}; | |
Countdown.prototype.start = function ( ) { | |
this.intervalId = window.setInterval( this.countdown, Countdown.SECOND ); | |
return this; | |
}; | |
Countdown.prototype.stop = function ( ) { | |
if ( this.intervalId !== null ) { | |
window.clearInterval( this.intervalId ); | |
} | |
return this; | |
}; | |
window.Countdown = Countdown; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment