JavaScript Countdown Timer

JavaScript Countdown Timer

My girlfriend and I are planning a trip to Montreal in a couple weeks and I’m out of town until then. I thought I would create this for her. In doing so I was able to practise using the Date() and Math() objects. The code is below,

 

var countdown = function () {

var future = new Date(2014, 4, 8, 13, 0, 0, 0);  //trip date
var now = new Date(); //time right now
var difference = future – now; 

var days = parseInt(difference / (86400000));
var hours = Math.floor((difference – (days * 86400000 ))/3600000);
var minutes = Math.floor((difference/1000 – (days * 86400 ) – (hours *3600 ))/60);
var secs = Math.floor((difference/1000 – (days * 86400 ) – (hours *3600 ) – (minutes*60)));

 

//add a zero is only one digit appears

if (days < 10) {
days = “0” + days;
}
if (hours < 10) {
hours = “0” + hours;
}
if (minutes < 10) {
minutes = “0” + minutes;
}
if (secs < 10) {
secs = “0” + secs;
}

document.getElementById(“timer”).firstChild.nodeValue = days + ” : ” + hours + ” : ” + minutes + ” : ” + secs; //used to display countdown on page

}

var playKiss = function() {
document.getElementById(“playsound”).play();
}

document.getElementById(“heart”).addEventListener(“click”, playKiss, false); // display when page loads

window.addEventListener(“load”, setInterval(countdown, 10), false);

 

The code can be cleaned up but it gets the job done. She liked it. 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s