JavaScript: Making a Digital Clock

To make a digital clock appear on a website you will need to use JavaScript (while also a bit of HTML and CSS).

This is the coding you will need.

Below, colours are used as follows:

  • Blue: for HTML
  • Red: for CSS
  • Green: for JavaScript
  • Black: for comments (these are just to help you understand what’s going on, comments don’t have to be in your actual code for your program to work.




<!DOCTYPE html>
<head>
  <title>JavaScript Clock</title>
  <style type="text/css">
    #clock { font-family: Arial; color: white; background-color: black; padding: 5px; }
  </style>
  <script type="text/javascript">

    function updateClock( )
    {
       // CREATING YOUR VARIABLES BY MAKING A "DATE" OBJECT - OBTAIN THE CURRENT TIME THROUGH METHODS
      var currentTime = new Date( );
      var currentHours = currentTime.getHours( );
      var currentMinutes = currentTime.getMinutes( );
      var currentSeconds = currentTime.getSeconds( );

       // FORMATTING THE CLOCK IN FORMAT "HH:MM:SS AM/PM"
       // Use a "ternary operator" to add a leading zero: "?" and ":"
      currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;       currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;        // Choose either "AM" or "PM" as appropriate, use a "ternary operator"
      var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";        // Convert the hours component to 12-hour format if needed
      currentHours = ( currentHours > 12 ) ? currentHours – 12 : currentHours;
       // Convert an hours component of "0" to "12"
      currentHours = ( currentHours == 0 ) ? 12 : currentHours;

       // DELIVERING YOUR OUTPUT
       // Compose the string for display
      var currentTimeString = currentHours + “:” + currentMinutes + “:” + currentSeconds + ” ” + timeOfDay;

       // CHANGING A HTML VALUE FOR THE DIGITAL CLOCK
      document.getElementById(“clock”).firstChild.nodeValue = currentTimeString;
      }
  
</script>
</head>

<body onload="updateClock(); setInterval('updateClock()', 1000)">
  <h1>A digital clock</h1>
  <p>This is a digital clock made JavaScript!</p>
  <div style="width: 15em; text-align: center; margin-top: 20px;">
   <span id="clock">&nbsp;</span>
  </div>
</body>

</html>