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
- HTML Structure: The HTML file sets up a simple structure with a
div
to display the clock. - CSS Styling: The CSS styles the clock, giving it a background, padding, and a border for visual appeal.
- 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 clockdiv
. - The clock is updated immediately when the script runs and then every second using
setInterval
.
How to Run
- Create three files:
index.html
,styles.css
, andscript.js
. - Copy the respective code snippets into each file.
- 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!