Simple HTML Countdown Page

Today I set out to make a simple HTML countdown. I was pleased with the results, so I have decided to share my source.

The HTML


<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
   <meta charset="utf-8" />
   <title>Countdown</title>
   <link href="style.css" rel="stylesheet" />
   <script src="countdown.js"></script>
</head>
<body onload="setTime()">
   <div id="console"></div>
</body>
</html>

This is all pretty straight forward, it is really just a blank page with references to the stylesheet to make it look pretty and javascript to make it work. The only thing really note worthy here is a div (console) to hold the calculated time and a call to setTime() when the body loads. (Doing it prior will cause an undefined element error.

The CSS


body
{
    background-color:black;
    margin: 0px; 
    padding: 0px;
    font:Andale Mono, monospace;
}

#console {
    background-color: black;
    color:white;
    height:120px; 
    position:absolute; 
    top:0px; 
    left:0px; 
    right:0px; 
    bottom:0px; 
    margin: auto; 
    text-align:center; 
    font-size:128px;
}

Once again this is pretty straight forward. By positioning it absolute at 0,0,0,0 and then assigning a margin #console stays nicely in the centre of the page. In retrospect I don’t think that the height is necessary for the element to remain centred.

The Javascript


function setTime() {
    var c = document.getElementById("console");

    var source = new Date();
    var target = new Date(2013, 9, 22, 20, 0, 0, 0);
    c.innerHTML = (target - source);
    setTimeout(setTime, 1);
}

source gets the current time from the default constructor of Date, and then target is the date that you are counting down to. Something worth mentioning is that the month field starts at 0, so to get October for example, you would use 9 (instead of the 10 that you might be used to)

Demo

Feel free to try out the HTML Countdown Sample for yourself and please let me know of any potential improvements (ex. pulling the time with php to avoid client time setting issues) in the comment section below.

Jesse Conner - October 21, 2013 - Code, Web