Happylab Logo
Published on

Day 2: JavaScript 30 Challenge - CSS + JS Clock

Authors
js30

Today we are making an analog clock using CSS and JavaScript. The main challenge is calculating the rotation degrees for the clock hands.

Key Points

  1. CSS transform-origin

    • Default is 50% (center)
    • For the clock hands, we need to set it to 100% so they rotate from the right end
    • transform-origin: 100%;
  2. CSS transition-timing-function

    • Controls animation speed curve
    • cubic-bezier allows custom timing curves
    • We use it to create a ticking effect
  3. JavaScript Date object methods

    • getSeconds(): Returns seconds (0-59)
    • getMinutes(): Returns minutes (0-59)
    • getHours(): Returns hours (0-23)

Implementation Steps

  1. Create clock hands using divs
  2. Style the hands with CSS transforms
  3. Use JavaScript to:
    • Get current time
    • Calculate degrees for each hand
    • Update hand rotations
    • Set interval to update every second

Code Explanation

The key is calculating the correct degrees for each hand:

function setDate() {
  const now = new Date()

  // Seconds
  const seconds = now.getSeconds()
  const secondsDegrees = (seconds / 60) * 360 + 90
  secondHand.style.transform = `rotate(${secondsDegrees}deg)`

  // Minutes
  const minutes = now.getMinutes()
  const minutesDegrees = (minutes / 60) * 360 + 90
  minHand.style.transform = `rotate(${minutesDegrees}deg)`

  // Hours
  const hours = now.getHours()
  const hoursDegrees = (hours / 12) * 360 + 90
  hourHand.style.transform = `rotate(${hoursDegrees}deg)`
}

Formula explanation:

  • For seconds: (current seconds / 60) * 360
  • For minutes: (current minutes / 60) * 360
  • For hours: (current hours / 12) * 360
  • Add 90 degrees to offset initial rotation

Challenges Encountered

  1. Initial hand position

    • Hands start at 9 o'clock position
    • Need to add 90 degrees to align properly
  2. Transition glitch at 0/360 degrees

    • Hands jump backwards when completing full rotation
    • Can be fixed by removing transition when needed

Additional Features to Try

  1. Add smooth movement for second hand
  2. Show digital time display
  3. Add date display
  4. Implement different clock styles

Today's project was relatively straightforward but taught important concepts about CSS transforms and JavaScript timing. The visual result is quite satisfying!

View Demo | Source Code