< BACK TO COMPONENTS

Step-by-Step Tutorial for Building a Web-based Digital Clock

Faraz

By Faraz -

Learn how to make a digital clock for your website using HTML, CSS, and JavaScript. Follow our easy tutorial for real-time clock functionality.


Step-by-Step Tutorial for Building a Web-based Digital Clock.jpg

Digital clocks have become a ubiquitous feature on websites, providing users with real-time information at a glance. If you've ever wondered how to incorporate this dynamic element into your web project, you're in the right place. In this beginner-friendly tutorial, we will guide you through the process of creating a digital clock using the trifecta of web development languages: HTML, CSS, and JavaScript.


Whether you're a web development novice or looking to expand your coding skills, this step-by-step guide will demystify the art of building and customizing digital clocks for your websites. By the end of this tutorial, you'll not only have a functional digital clock but also the knowledge to tailor it to your unique design preferences.


So, let's dive into the world of web-based digital clocks and start creating your very own!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our digital clock.


After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


Let's break it down step by step:


1. <!DOCTYPE html>: This is the document type declaration and specifies that this is an HTML5 document.


2. <html lang="en">: This is the opening tag of the HTML document. It indicates that the document is written in English (en stands for English). All the content of the web page will be enclosed within the <html> tags.


3. <head>: This is the opening tag of the document's head section. The head section typically contains metadata and other information about the web page, but it doesn't display any visible content to the user.


  • <title>JavaScript Digit Clock</title>: This sets the title of the web page, which is displayed in the browser's title bar or tab. In this case, it's "JavaScript Digit Clock."
  • <meta charset="UTF-8" />: This meta tag specifies the character encoding for the web page. UTF-8 is a widely used character encoding that supports a wide range of characters and symbols.
  • <meta name="viewport" content="width=device-width" />: This meta tag is often used for making web pages responsive to different screen sizes. It tells the browser to adjust the page's width to the device's width, ensuring that it looks good on various devices.
  • <link rel="stylesheet" href="styles.css" />: This line links an external CSS (Cascading Style Sheets) file named "styles.css" to the HTML document. This CSS file is used to style the content of the web page.
  • <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;700;900&display=swap" rel="stylesheet">: This line links an external stylesheet from Google Fonts, specifically the "Poppins" font with different weights (500, 700, and 900). This font will be used for styling text on the web page.

4. <body>: This is the opening tag of the document's body section. The body section contains all the visible content of the web page.


  • <div id="MyClockDisplay" class="clock" onload="showTime()"></div>: Inside the body section, there is a <div> element with the id "MyClockDisplay" and a class "clock." It also has an "onload" attribute set to "showTime()." This suggests that when the page loads, a JavaScript function called "showTime()" will be executed. This function displays a digital clock.
  • <script src="script.js"></script>: This line includes an external JavaScript file named "script.js." JavaScript is a programming language used for adding interactivity to web pages. The "script.js" file contains the code for the "showTime()" function and other JavaScript functionality for the digital clock.

This is the basic structure of our digital clock using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the digital clock is in place, the next step is to add styling to the clock using CSS.


Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our clock. Let's break it down:


1. body: This selector targets the <body> element of the web page, which represents the entire content area.


  • font-family: 'Poppins', 'Courier New', Courier, monospace;: This line sets the font family for text within the <body> element. It specifies a preference for the "Poppins" font, but if that font is unavailable, it will fall back to "Courier New," "Courier," or any generic monospace font.
  • background-color: #1f1d2b;: This line sets the background color of the entire web page's content area to a dark shade (#1f1d2b).

2. .clock: This selector targets elements with the class "clock." It is applied to a specific <div> element in the HTML code, as indicated by class="clock".


  • position: absolute;: This property specifies that the element should be positioned absolutely within its containing element. It means the element's position will be based on the top and left properties.
  • top: 50%;: This property positions the element vertically at the midpoint of its containing element (in this case, the browser window).
  • left: 50%;: This property positions the element horizontally at the midpoint of its containing element.
  • transform: translateX(-50%) translateY(-50%);: This CSS rule is used in combination with the top and left properties to center the element both vertically and horizontally within its container. It uses the transform property to move the element 50% of its own width to the left (-50%) and 50% of its own height upward (-50%), effectively centering it.
  • color: #ffd791;: This sets the text color inside elements with the class "clock" to a light yellowish color (#ffd791).
  • font-size: 60px;: This sets the font size for text inside elements with the class "clock" to 60 pixels.
  • letter-spacing: 7px;: This property adds extra spacing between letters in the text inside elements with the class "clock." It increases the letter spacing to 7 pixels.

This will give our clock an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  font-family: 'Poppins', 'Courier New', Courier, monospace;
  background-color: #1f1d2b;
}

.clock {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  color: #ffd791;
  font-size: 60px;
  letter-spacing: 7px;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. This JavaScript code defines a function called showTime() that displays a digital clock on a web page. Let's break it down step by step:


1. function showTime() {: This line begins the definition of the showTime function in JavaScript.


2. var date = new Date();: This line creates a new JavaScript Date object, which represents the current date and time.


3. var h = date.getHours();: This line extracts the current hour from the date object and stores it in the variable h.


4. var m = date.getMinutes();: This line extracts the current minutes from the date object and stores it in the variable m.


5. var s = date.getSeconds();: This line extracts the current seconds from the date object and stores it in the variable s.


6. var session = "AM";: This line initializes a variable session with the value "AM." This variable will be used to represent whether it's morning (AM) or afternoon/evening (PM).


7. if (h == 0) { h = 12; }: This if statement checks if the value of h is 0 (midnight). If it is, it sets h to 12 to represent 12:00 AM.


8. if (h > 12) { h = h - 12; session = "PM"; }: This if statement checks if the value of h is greater than 12. If it is, it subtracts 12 from h to represent the time in the afternoon/evening (e.g., 13 becomes 1), and it sets the session variable to "PM."


9. h = (h < 10) ? "0" + h : h;, m = (m < 10) ? "0" + m : m;, s = (s < 10) ? "0" + s : s;: These lines check if h, m, or s are less than 10 (single-digit values). If they are, a leading "0" is added to them to ensure that the time is displayed in a consistent format with two digits for hours, minutes, and seconds.


10. var time = h + ":" + m + ":" + s + " " + session;: This line combines the h, m, s, and session variables to create a formatted time string, like "hh:mm:ss AM/PM."


11. document.getElementById("MyClockDisplay").innerText = time;: This line updates the content of an HTML element with the id "MyClockDisplay" to display the time string. This element is the digital clock element on the web page.


12. setTimeout(showTime, 1000);: This line sets a timeout to call the showTime function again after 1000 milliseconds (1 second). This creates a continuous loop, updating the clock every second.


13. The final } closes the showTime function.


14. showTime();: This line calls the showTime function once when the page loads to initially display the time.


Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

function showTime(){
  var date = new Date();
  var h = date.getHours();
  var m = date.getMinutes();
  var s = date.getSeconds();
  var session = "AM";
  
  if(h == 0){
      h = 12;
  }
  
  if(h > 12){
      h = h - 12;
      session = "PM";
  }
  
  h = (h < 10) ? "0" + h : h;
  m = (m < 10) ? "0" + m : m;
  s = (s < 10) ? "0" + s : s;
  
  var time = h + ":" + m + ":" + s + " " + session;
  document.getElementById("MyClockDisplay").innerText = time;
  
  setTimeout(showTime, 1000);
  
}

showTime();

Final Output:

Step-by-Step Tutorial for Building a Web-based Digital Clock.gif

Conclusion:

Congratulations! You've successfully created a digital clock for your website. Feel free to customize it further, add additional features, or integrate it into other projects.


In this tutorial, we've covered the basics of creating a digital clock using HTML, CSS, and JavaScript. With this foundation, you can explore more advanced features and create unique clocks to enhance your web projects. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post