Ws 4
Ws 4
Objective
Create a digital clock that displays the current time and updates every second.
Instructions
1. Create three files: index.html , styles.css , and script.js .
Code to Type
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Digital Clock</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="clock">
<h1>Digital Clock</h1>
<div id="time">00:00:00</div>
</div>
<script src="script.js"></script>
</body>
</html>
body {
background-color: #222;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: 'Courier New', Courier, monospace;
}
.clock {
text-align: center;
}
#time {
font-size: 4em;
margin-top: 20px;
}
script.js
function updateTime() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2,
'0');
const seconds = String(now.getSeconds()).padStart(2,
'0');
timeDisplay.textContent = `${hours}:${minutes}:${second
s}`;
}
updateTime();
Key Points
setInterval is used to update the time every second.
Leading zeros are added to hours, minutes, and seconds for consistent
display.
CSS Flexbox centers the clock both vertically and horizontally on the page.
The clock updates in real-time without the need to refresh the page.