DEV Community

Mohammad Shahzeb Alam
Mohammad Shahzeb Alam

Posted on

Today I Learned: Vanilla JavaScript Clock πŸ•’

Today I built a functional analog clock using just HTML, CSS, and Vanilla JavaScript β€” no libraries or frameworks involved!

It was a great way to practice working with the DOM and time-based JavaScript logic.

🧠 How It Works
In JavaScript, I created a function called setDate() which runs every second using setInterval().

Here's what happens inside setDate():

  1. I use new Date() to get the current time.

  2. From that date object, I extract:

-seconds

-minutes

-hours

  1. I then convert each time value into degrees so I can rotate the clock hands correctly.

  2. Finally, I apply the rotation using element.style.transform on the second, minute, and hour hands.

This creates the effect of a working analog clock ticking in real time! 🎯

πŸ” Why the +90 Degrees?
In CSS, a rotation of 0deg points to the right (3 o'clock).
But clocks start at the top (12 o'clock), so I had to add +90 degrees to shift the rotation and make it accurate.

πŸ–ΌοΈ Here's What It Looks Like

Top comments (0)