Building a JS Clock: Part 1

How can I make a real time digital (no analog) clock with vanilla JS, html, and css?

Creating a real-time digital clock using vanilla JavaScript, HTML, and CSS is straightforward. Here’s a simple example to help you get started.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Digital Clock</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="clock" id="clock"></div>
    <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #282c34;
    color: white;
    font-family: 'Arial', sans-serif;
    font-size: 48px;
}

.clock {
    padding: 20px;
    border: 2px solid #61dafb;
    border-radius: 10px;
    text-align: center;
    background-color: rgba(255, 255, 255, 0.1);
}

JavaScript (script.js)

function updateClock() {
    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');

    const clockElement = document.getElementById('clock');
    clockElement.textContent = `${hours}:${minutes}:${seconds}`;
}

// Update the clock immediately and then every second
updateClock();
setInterval(updateClock, 1000);

How It Works

  1. HTML Structure: The HTML file sets up a simple structure with a div to display the clock.
  2. CSS Styling: The CSS styles the clock, giving it a background, padding, and a border for visual appeal.
  3. JavaScript Logic:
  • The updateClock function retrieves the current time, formats it to ensure two-digit hours, minutes, and seconds, and updates the content of the clock div.
  • The clock is updated immediately when the script runs and then every second using setInterval.

How to Run

  1. Create three files: index.html, styles.css, and script.js.
  2. Copy the respective code snippets into each file.
  3. Open index.html in your web browser to see the digital clock in action!

This simple setup provides a functional digital clock that updates in real time. You can further customize styles and formats as desired!



Leave a Reply

Your email address will not be published. Required fields are marked *