Created
March 28, 2013 09:17
-
-
Save rayfranco/5261859 to your computer and use it in GitHub Desktop.
jquery.countdown.coffee : a minimal jquery plugin to launch a countdown with a simple API
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
$ = jQuery | |
defaults = | |
kickoff: "March 28, 2017 18:30:00" | |
onStart: (kickoff, el) -> | |
console and console.log "Countdown will start to #{ kickoff }" | |
onChange: (counter,el) -> | |
if not el | |
console.log "Countdown state : #{ counter.days } days, #{ counter.hours } hours, #{ counter.minutes } minutes, #{ counter.seconds } seconds left." | |
else | |
el.text "#{ counter.days } days, #{ counter.hours } hours, #{ counter.minutes } minutes, #{ counter.seconds } seconds left." | |
onFinish: () -> | |
alert "Yay ! It's a final countdown !" | |
class Countdown | |
# Constructor | |
constructor: (@el, settings = {}) -> | |
@settings = $.extend {}, defaults, settings | |
@counter = | |
seconds: 0 | |
minutes: 0 | |
hours: 0 | |
days: 0 | |
kickoff = @el.data('kickoff') or @settings.kickoff | |
@kickoff = new Date(kickoff) | |
@start.call(@) | |
@el | |
# Counter | |
count: () -> | |
now = new Date() | |
diff = new Date @kickoff - now | |
left = Math.floor(diff.valueOf() / 1000) | |
@counter.seconds = Math.floor(left / 1) % 60 | |
@counter.minutes = Math.floor(left / 60) % 60 | |
@counter.hours = Math.floor(left / 3600) % 24 | |
@counter.days = Math.floor(left / 86400) % 86400 | |
if diff < 0 | |
@settings.onFinish() | |
return | |
setTimeout () => | |
@count.call(@) | |
, 1000 | |
@settings.onChange @counter, @el | |
# Start the countdown | |
start: () -> | |
if not @kickoff | |
throw new Error 'Cannot start countdown without a kickoff date' | |
@count() | |
@settings.onStart @kickoff, @el | |
(($) -> | |
$.fn.countdown = (settings) -> | |
new Countdown(@, settings) | |
)(jQuery) |
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
<!doctype html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>It's a final countdown</title> | |
</head> | |
<body> | |
<div id="timer" data-kickoff="March 27, 2013 18:50:50"></div> | |
<script src="jquery.js"></script> | |
<script src="jquery.countdown.js"></script> | |
<script> | |
$(function(){ | |
$('#timer').countdown() | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment