Looking for a JavaScript digital clock in 12-hour format? This code, written in pure vanilla JS, creates a sleek and stylish timepiece for your webpage. The script initializes variables for hours, minutes, seconds, and AM/PM, displaying the current time in a user-friendly format.
The clock updates every second, ensuring real-time accuracy. Easily customizable, it’s perfect for adding a touch of functionality and elegance to your site.
How to Create JavaScript Digital Clock With 12 Hour Format
1. In your HTML file, create a container where you want the clock to appear. For example:
<div class='time'></div> <h1>This is what you are looking for.</h1> <h1>Pure Vanilla JS</h1>
Feel free to customize the styling by adding additional HTML elements and classes.
2. Apply the desired styles to your clock using the following CSS code. This example provides a simple dark theme, but you can customize it to match your website’s design:
body { background: black; } .time, h1 { font-family: Helvetica; font-size: 6em; color: white; }
3. Now, add the JavaScript code to your file. Copy and paste the following script, which initializes variables for hours, minutes, seconds, and AM/PM. The displayTime
function formats the time and continuously updates the clock every second.
// A simple vanilla JS clock // Initilize variables for date, hour, minute, second, am or pm, and the final displayed time var d, h, m, s, ampm, time; // Your clock! function displayTime() { d = new Date(); h = d.getHours(); m = d.getMinutes(); s = d.getSeconds(); ampm = h >= 12 ? 'pm' : 'am'; h = h % 12; // Adds zeros to single digit times if (h <= 9) { h = '0' + h; } if (m <= 9) { m = '0' + m; } if (s <= 9) { s = '0' + s; } // Assign time format to variable. If you want to change how time is displayed do it here // Example time = h + ":" + m; time = h + ":" + m + ":" + s + " " + ampm; // Print your clock to an element. document.getElementsByClassName("time")[0].innerHTML = time; // Refreshes clock every second. If you're just using minutes change to 60000 setTimeout(displayTime, 1000); } // Run your baller clock! displayTime();
That’s all! hopefully, you’ve successfully implemented a digital clock with a 12-hour format on your webpage. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.