HTML5 | How to create a simple Clock using JavaScript

Web Project

In this project we will be learning to design a simple digital clock using HTML5, CSS3 and JavaScript.

Requirement

For this project we can use any text editor like Notepad++, SublimeText, gEdit, TextMate, Coda, Brackets etc.

In the above video Brackets has been used which is an open source software and can be downloaded from their website brackets.io

Files

For this project we will need three files namely

  • index.html
  • script.js
  • style.css

index.html


<!DOCTYPE html>
<html>
    <head>
        <title>Clock</title>
        <script type="text/javascript" src="script.js"></script>
        <link type="text/css" rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="clock">
            <span id="hr">00</span>
            <span> : </span>
            <span id="min">00</span>
            <span> : </span>
            <span id="sec">00</span>
        </div>
    </body>
</html>

script.js


var d,h,m,s,animate;

function init(){
    d=new Date();
    h=d.getHours();
    m=d.getMinutes();
    s=d.getSeconds();
    clock();
};

function clock(){
    s++;
    if(s==60){
        s=0;
        m++;
        if(m==60){
            m=0;
            h++;
            if(h==24){
                h=0;
            }
        }
    }
    $('sec',s);
    $('min',m);
    $('hr',h);
    animate=setTimeout(clock,1000);
};

function $(id,val){
    if(val<10){
        val='0'+val;
    }
    document.getElementById(id).innerHTML=val;
};

window.onload=init;

style.css


*{
    margin:0;
    padding:0;
    font-family:sans-serif;
    font-size:36px;
}

.clock{
    text-align:center;
    width:auto;
    height:auto;
}