JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<div class="clock-container">
    <div class="clock" id="clock">
      <!-- Numbers will be dynamically generated using JavaScript -->
    </div>
  </div>

CSS

.clock-container {
  text-align: center;
}

.clock {
  position: relative;
  width: 200px;
  height: 200px;
  border: 2px solid #333;
  border-radius: 50%;
}

.number {
  position: absolute;
  width: 100%;
  /* Adjust the width as needed */
  height: 115%;
  /* Adjust the height as needed */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  /* Adjust the font size as needed */
  color: #333;
  transform-origin: 50% 90%;
  /* Adjust the transform origin for proper rotation */
  bottom: 39%;
}

.hand {
  position: absolute;
  top: 25%;
  left: 50%;
  transform-origin: bottom;
  background-color: #333;
}

.hour {
  width: 6px;
  height: 50px;
}

.minute {
  width: 4px;
  height: 70px;
  top: 15%;
}

.second {
  width: 2px;
  height: 80px;
  top: 10%;
  left: 51%;
}

JavaScript

document.addEventListener('DOMContentLoaded', function() {
    const clock = document.getElementById('clock');
    const numbers = Array.from({ length: 12 }, (_, index) => index + 1);

    numbers.forEach(number => {
      const numberDiv = document.createElement('div');
      numberDiv.className = 'number';
      numberDiv.style.transform = `rotate(${number * 30}deg)`;
      numberDiv.textContent = number;
      clock.appendChild(numberDiv);
    });

    function calculateRotation(unit, hours, minutes) {
      let value;
      if (unit === 'hours') {
        value = (hours % 12) + minutes / 60;
        return `rotate(${value * 30}deg)`;
      } else if (unit === 'minutes') {
        value = minutes;
        return `rotate(${value * 6}deg)`;
      } else {
        value = new Date().getSeconds();
        return `rotate(${value * 6}deg)`;
      }
    }

    function updateClock() {
      const time = new Date();
      const hourHand = document.querySelector('.hand.hour');
      const minuteHand = document.querySelector('.hand.minute');
      const secondHand = document.querySelector('.hand.second');

      hourHand.style.transform = calculateRotation('hours', time.getHours(), time.getMinutes());
      minuteHand.style.transform = calculateRotation('minutes', time.getMinutes());
      secondHand.style.transform = calculateRotation('seconds');
    }

    const createHand = (className, width, height, top, left) => {
      const hand = document.createElement('div');
      hand.className = `hand ${className}`;
      hand.style.width = `${width}px`;
      hand.style.height = `${height}px`;
      hand.style.top = `${top}%`;
      hand.style.left = `${left || 50}%`;
      clock.appendChild(hand);
      return hand;
    };

    createHand('hour', 6, 50, 25);
    createHand('minute', 4, 70, 15);
    createHand('second', 2, 80, 10, 51);

    setInterval(updateClock, 1000);
    updateClock(); // Initial clock update
  });