Modern minimalistic flat analog clock with css js and startup animation


Modern minimalistic flat analog clock with css js and startup animation Tutorial by Mirko Zovko | 10. Aug. 2020.

In this tutorial I’ll show you how to create a minimalistic analog clock with css, vanilla js and simple startup animation.

At first I was planning to create all the structure in the js, but I wanted to make it a bit simpler so all the structure is written in html and it looks like this:

  • clock - is a container class for our minimalistic analog clock, and with it I make 2 more classes that you can use, dark and white for different style, color of the clock.
  • dot - is center element where all clock hands starts, it’s only for esthetic there so that clock look a bit nicer
  • handles:
    • sec - is hand for seconds
    • min - is hand for minutes
    • hour - is hand for hour
    They all have one more class, and that is animate class. It is used for the first animation of handles when the clock is starting.

There are only a few simple tricks in css that I used to make dot and hands of the clock in the middle. First of all .clock (container) I put to display flex and with justify-content and align-items style attributes I make all center. Then with transform-origin attribute I move the point of the handles rotation in the middle bottom part and with the percentage value I wrote their height and top position. With that you can easily change clock ( container ) width and height and everything will be where it should.

For vanilla js code I created everything in one function initAnalogClock(elem). So to start your clock you have to call initAnalogClock where elem is the container of your clock.

Steps of the js code for analog clock are:

  • Getting all html elements for clock hands
  • Run function runClock first time and every next second with setInterval. In the runClock function I get:
    • Current time
    • Get current second, minute and hour
    • Adding rotate transformation attribute to handles. You can see on the image below the starting position of the handles.
  • On function start removing animate class after animation is finished. In my case animation is 600ms long.

Modern minimalistic flat analog clock with css js and startup animation

I noticed a lot of clocks made in css and vanilla js but I didn’t notice one thing and that is the hour handle to move a bit more like a real clock. Not to move on clock change, but to move on minute change. For example with this code you hour handle in 3:30h will be between 3 and 4 not on 3 until 4 comes out. So to make that possible I’m not taking hours directly for clock handling, I’m getting decimal hour time to make it more realistic where it stands. You can see the code below.

Few usage example you can check on jsFiddle or on Codepen

I hope you liked this article. If you have some suggestion or idea feel free to write in comment section bellow. Enjoy! :)