N. Achyut javascript,Uncategorized Digital Watch using JavaScript | Basic JavaScript Project

Digital Watch using JavaScript | Basic JavaScript Project

Create a Digital Clock using JavaScript

Here, With this article you will learn how to create Digital Clock with standard format.

watch function is defined and we created a variable called date. and using the get method of javascript we store the data in h,m,s variable.

    var date = new Date();
    var h = date.getHours(); // 0 - 23
    var m = date.getMinutes(); // 0 - 59
    var s = date.getSeconds(); // 0 - 59

The complete JavaScript code is given below : watch.js file

function watch(){    
    var date = new Date();
    var h = date.getHours(); // 0 - 23
    var m = date.getMinutes(); // 0 - 59
    var s = date.getSeconds(); // 0 - 59
    var session = "AM";
    
    if(h == 0){
        h = 12;
    }
    
    if(h > 12){
        h = h - 12;
        session = "PM";
    }
    
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;
    
    var time = h + ":" + m + ":" + s + " " + session;
    document.getElementById("watch").innerText = time;
    document.getElementById("watch").textContent = time;
    
    setTimeout(watch, 1000);
    
}

watch(); //calling function

In the index.html file we called the function using the onload event.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="clock">
        <h1>Welcome to Utshuk Watch</h1>
        <div id="watch" class="watch" onload="watch()"></div>
    </div>
     
 <script src="watch.js"></script>   
</body>
</html>

Now the time is to styling your watch, in order to make good style we used simple css code.

body {
    background:coral;
}

h1{
    text-align: center;
    margin-top: 150px;

}

.watch{
    border: springgreen 2px solid;
}

.watch {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    color: whitesmoke;
    font-size: 60px;
    font-family: Orbitron;
    letter-spacing: 7px;
}

Related Post