- Published on
Day 2: JavaScript 30 Challenge - CSS + JS Clock
- Authors

- Name
- irisjustdoit
- @irisjustdoit

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
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%;
CSS transition-timing-function
- Controls animation speed curve
- cubic-bezier allows custom timing curves
- We use it to create a ticking effect
JavaScript Date object methods
- getSeconds(): Returns seconds (0-59)
- getMinutes(): Returns minutes (0-59)
- getHours(): Returns hours (0-23)
Implementation Steps
- Create clock hands using divs
- Style the hands with CSS transforms
- 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
Initial hand position
- Hands start at 9 o'clock position
- Need to add 90 degrees to align properly
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
- Add smooth movement for second hand
- Show digital time display
- Add date display
- 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!
