Categories :

How to make a digital watch with JavaScript, CSS and HTML?

Hello JavaScript learners, in this tutorial will help you to clear understand on JS Date() Object which is default or built in object in JavaScript. You have already know html, CSS and little JS, ok fine this tutorial is for you. This tutorial voice is in Bengali.

See the video on YouTube

See the code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS App</title>

    <style>
        * {
            box-sizing: border-box;
        }
        
        body {
            width: 700px;
            margin: 0 auto;
        }
        
        #watch {
            padding-left: 50px;
            padding-top: 250px;
        }
        
        .display {
            width: 400px;
            height: 400px;
            padding: 50px;
            font-size: 32px;
            background-color: rgb(9, 38, 136);
            color: cornsilk;
        }
    </style>
</head>

<body>
    <div class="display">
        <span id="watch"></span><span id="ampm"></span>
        <p>Developed by Pranta</p>
    </div>

    <script>
        window.onload = function() {
            getTime();
        }

        function getTime() {
            let date = new Date();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();

            // add a extra 0 if less than 10
            m = checkTime(m);
            s = checkTime(s);

            document.getElementById('watch').innerHTML = h + ":" + m + ":" + s + " ";

            setInterval("getTime()", 1000);

        }

        function checkTime(x) {
            if (x < 10) {
                x = "0" + x;
            }
            return x;
        }

        let d = new Date();
        let a = d.getHours();

        if (a < 12) {
            document.getElementById('ampm').innerHTML = "AM";
        } else {
            document.getElementById('ampm').innerHTML = "PM";
        }
    </script>
</body>

</html>

Leave a Reply

Your email address will not be published.