Digital Clock using HTML | CSS | JS
Hello! Let's learn how we can make Digital clock using Html, Css and JavaScript.
This is a simple and basic project where we can see use of Date() function in javascript. Date() is an inbuilt javascript function where we can use to show date and time in the web page. With the help of date object we can use getHours() to get current hour, getMinutes() to get current minute, getSeconds() to get current seconds.
In order to run the clock every second we will use setTimeout() function.
Please follow the below code and get started 💻.
HTML Code
<body>
<div class="container">
<h2 class="hr" id="hr"></h2>
<span>:</span>
<h2 class="min" id="min"></h2>
<span>:</span>
<h2 class="sec" id="sec"></h2>
</div>
</body>
CSS Code
body {
margin: 0;
padding: 0;
font-family: 'Ubuntu Mono', monospace;
display: flex;
min-height: 100vh;
background: #111;
}
.container {
margin: auto;
display: flex;
align-items: center;
font-size: 3rem;
color: #0fA;
}
JavaScript Code
// selectors
let hrEle = document.getElementById('hr');
let minEle = document.getElementById('min');
let secEle = document.getElementById('sec');
// function to display current time
function showTime() {
let date = new Date();
let hr = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();
hr = hr < 10 ? '0'+hr : hr;
min = min < 10 ? '0'+min : min;
sec = sec < 10 ? '0'+sec : sec;
hrEle.innerHTML = hr;
minEle.innerHTML = min;
secEle.innerHTML = sec;
// run showTime() after every seconds
setTimeout(showTime, 1000);
}
// calling showTime function
showTime();
Output
I hope you find this helpful and interesting. Thank you for visiting my blog.
Code by - AltafAlam Shaikh
Topic covered - Date(), setTimeout() function in javascript
Technology used - Html, Css, JavaScript
Font used - Ubuntu mono (https://fonts.google.com/specimen/Ubuntu+Mono)