Adding a live clock to your website can be a nice touch for your visitors, providing them with the current time while they browse your site. In this tutorial, we will show you how to add a simple live clock using HTML and JavaScript.
Step 1: Create a container for the clock
First, we need to create a container in our HTML file that will hold the live clock. We can simply use a <div> element with an id attribute, so that we can easily target it later with JavaScript. Add the following code to your HTML file:
Step 2: Create the JavaScript function
Now, we need to create a JavaScript function that will update the live clock’s content with the current time. Add the following script tag to your HTML file, preferably just before the closing </body> tag:
function updateClock() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
// Add leading zeros if necessary
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds : seconds;
var timeString = hours + ‘:’ + minutes + ‘:’ + seconds;
document.getElementById(‘liveClock’).innerHTML = timeString;
}
</script>
Step 3: Call the function and set an interval
Finally, we need to call the updateClock() function and set an interval to update the clock every second. Add the following code inside the <script> tag, after the updateClock() function:
setInterval(updateClock, 1000); // Update clock every 1000 milliseconds (1 second)
Final Result
Now you should have a working live clock on your web page. The complete HTML file should look like this:
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Live Clock Example</title>
</head>
<body>
<div id=”liveClock”></div>
<script>
function updateClock() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds : seconds;
var timeString = hours + ‘:’ + minutes + ‘:’ + seconds;
document.getElementById(‘liveClock’).innerHTML = timeString;
}
updateClock();
setInterval(updateClock, 1000);
</script>
</body>
</html>
And that’s it! You now have a simple and functional live clock on your website. You can further customize the appearance of the clock using CSS, or even add more features such as displaying the current date.