JavaScript Analog Clock Source Code

JavaScript Analog Clock Source Code
Code Snippet:Analog Clock with Text Labels
Author: Wade Christensen
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 5,160
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript source code helps you to create an analog clock widget with smooth sweeping clock hands. It displays the time with long-form text labels for the hour and minute. The clock widget is purely built with CSS and Vanilla JavaScript without using SVG or images.

You can use this analog clock widget to display day, date, and time on a news or magazine website. Similarly, it can also be used to indicate the time for a specific purpose like a Quiz page or online exam interface to keep the students updated with time.

How to Create JavaScript Analog Clock

1. In order to create an analog clock, create the HTML structure for the clock as follows:

<div class="container">
    <div id="clock">
    <div class="dial"></div>
    <ul id="time-display" class="display-text">
      <li id="hour-display"></li>
      <li id="minute-display"></li>
    </ul>
    <ul id="calendar-display" class="display-text">
      <li id="day-display"></li>
      <li id="month-display"></li>
      <li id="date-display"></li>
    </ul>
    <div id="second-hand" class="hand">
      <div class="ring"></div>
    </div>
    <div id="minute-hand" class="hand"></div>
    <div id="hour-hand" class="hand"></div>
  </div>
</div>

2. After that, style the clock widget using the following CSS styles. If you want to customize the clock interface, you can set the custom background, size (width & height), margin, and padding value.

.container {
    background: #7F00FF;  /* fallback for old browsers */
    background: -webkit-linear-gradient(to right, #E100FF, #7F00FF);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(to right, #E100FF, #7F00FF); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    width: 100%;
    min-height: 520px; 
    text-align: center;
    padding: 50px;
    box-sizing: border-box;
}

#clock {
  position: relative;
  grid-area: content;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  border: double 10px #39454b;
  background: linear-gradient(-45deg, #39454b 20%, #101017);
  box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.5);
  margin: 10px auto;
}

.dial {
  position: absolute;
  top: calc(50% - 10px);
  left: calc(50% - 10px);
  width: 20px;
  height: 20px;
  box-sizing: border-box;
  border-radius: 50%;
  border: dotted 1px #101017;
  background: #4c5c64;
  z-index: 1;
}

/* Clock hands */
.hand {
  position: absolute;
  transform-origin: 0px center;
  /* Fix aliasing caused by transform: rotate() */
  outline: 1px solid transparent;
}

#hour-hand {
  /* center hand */
  top: calc(50% - 2px);
  left: 50%;
  width: 80px;
  height: 2px;
  border: 1px solid #fff;
  border-radius: 3px;
  background: #b7ddf0;
  z-index: 2;
}

#minute-hand {
  /* center hand */
  top: calc(50% - 2px);
  left: 50%;
  width: 120px;
  height: 2px;
  border: 1px solid #fff;
  border-radius: 3px;
  background: #b7ddf0;
  z-index: 3;
}

#second-hand {
  /* center hand */
  top: calc(50% - 1px);
  left: 80px;
  width: 200px;
  height: 2px;
  border-radius: 1px;
  background: #b7ddf0;
  transform-origin: 70px center;
  z-index: 5;
}

#second-hand .ring {
  width: 12px;
  height: 10px;
  margin-top: -5px;
  margin-left: 15px;
  background: transparent;
  border: 1px solid #b7ddf0;
  border-radius: 50%;
  z-index: 11;
}

/* Long form text displays */
.display-text li {
  list-style-type: none;
  font-size: 16px;
  line-height: 20px;
  font-family: Arial, Helvetica, sans-serif;
  text-transform: uppercase;
  color: #fff;
}

#time-display {
  position: absolute;
  top: 25%;
  left: calc(50% - 75px);
  min-width: 150px;
  margin: 0;
  text-align: center;
  transition: 1s ease-in;
}

#time-display li {
  display: block;
}

#calendar-display {
  position: absolute;
  top: 75%;
  left: calc(50% - 75px);
  min-width: 150px;
  margin: 0;
  text-align: center;
}

#calendar-display li {
  display: inline-block;
}

3. Finally, add the following JavaScript source code between the <script> tag before closing the body tag in order to functionalize the analog clock.

// Setters
const setTimeString = timeUnit => {
  // String representations of time numbers
  const timeStrings = {
    0: "",
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine",
    10: "ten",
    11: "eleven",
    12: "twelve",
    13: "thirteen",
    14: "fourteen",
    15: "fifteen",
    16: "sixteen",
    17: "seventeen",
    18: "eighteen",
    19: "nineteen",
    20: "twenty",
    30: "thirty",
    40: "fourty",
    50: "fifty",
    60: "sixty" };


  if (timeUnit < 20) {
    return timeStrings[timeUnit];
  } else {
    const digitOne = timeStrings[Math.floor(timeUnit / 10) * 10];
    const digitTwo = timeStrings[timeUnit % 10] ?
    timeStrings[timeUnit % 10] :
    0;
    if (digitTwo !== 0) {
      return `${digitOne} ${digitTwo}`;
    } else {
      return digitOne;
    }
  }
};

(function () {
  // Getters
  const getDomElements = () => {
    const hourDisplay = document.getElementById("hour-display");
    const minuteDisplay = document.getElementById("minute-display");
    const dayDisplay = document.getElementById("day-display");
    const monthDisplay = document.getElementById("month-display");
    const dateDisplay = document.getElementById("date-display");
    const hourHand = document.getElementById("hour-hand");
    const minuteHand = document.getElementById("minute-hand");
    const secondHand = document.getElementById("second-hand");

    return {
      hourDisplay,
      minuteDisplay,
      dayDisplay,
      monthDisplay,
      dateDisplay,
      hourHand,
      minuteHand,
      secondHand };

  };

  const getCurrentTime = () => {
    const date = new Date();
    const time = date.getTime();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const milliseconds = date.getMilliseconds();

    return {
      date,
      time,
      // Adjust hours to 12 hour clock
      hours: hours > 12 ? hours - 12 : hours,
      minutes,
      seconds,
      milliseconds };

  };

  const setDateDisplay = currentTime => {
    const nowDateString = currentTime.toDateString();
    const dayString = nowDateString.slice(0, 3);
    const monthString = nowDateString.slice(4, 7);
    const dateString = nowDateString.slice(8, 10);

    return {
      dayString,
      monthString,
      dateString };

  };

  // Rendering
  const rotateHand = (timeUnit, factor, hand) => {
    // -90 degress accomodates for initial css layout position
    const position = timeUnit * factor - 90;
    hand.style.transform = `rotate(${position}deg)`;
  };

  const renderClock = () => {
    const domElements = getDomElements();
    const currentTime = getCurrentTime();
    // Hand values for animation
    // Seconds, minutes, hours reflect 100ms setInterval() iteration
    const seconds =
    (currentTime.seconds * 1000 + currentTime.milliseconds) / 1000;
    const minutes = (currentTime.minutes * 60 + seconds) / 60;
    const hours = (currentTime.hours * 60 + minutes) / 60;

    // Display strings for long-form readout
    const hourString = setTimeString(currentTime.hours);
    const minuteString = setTimeString(currentTime.minutes);
    let { dayString, monthString, dateString } = setDateDisplay(
    currentTime.date);


    // Populate DOM Elements
    domElements.hourDisplay.innerHTML = hourString;
    domElements.minuteDisplay.innerHTML = minuteString;
    domElements.dayDisplay.innerHTML = `${dayString} | `;
    domElements.monthDisplay.innerHTML = `${monthString} | `;
    domElements.dateDisplay.innerHTML = dateString;

    // Rotate Hands
    rotateHand(seconds, 6, domElements.secondHand);
    rotateHand(minutes, 6, domElements.minuteHand);
    rotateHand(hours, 30, domElements.hourHand);
  };

  const run = () => {
    setInterval(() => {
      renderClock();
    }, 100);
  };

  run();
})();

That’s all! hopefully, you have successfully integrated this analog clock widget into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X