Day 2 – JavaScript30 — JS and CSS Clock

Today is my second day of JavaScript30 by @wesbos. If you don’t know what I am talking about, go ahead and take the course yourself. If you want to catch up, then visit my JavaScript30 series.

Our Problem

Today we are going to make an analog clock with CSS and JavaScript. To do that we are going to need the starter folder from the course.

What do we have?

We have a starter file with lots very little HTML and CSS.

Solution

Here is how I learned to make the clock work:

  1. First of all, we explored the transform property of CSS and how it can make HTML elements animate. I think it is quite obvious why we did it because we need to change the position of the needles every second. So here the properties that we used:
    1. transform-origin: This property changes the origin or the point of origin around which the transform property is applied.
    2. transform: In our case, we need to change the angle of the needles; hence we are going to use rotate.
  2. Now, to keep the needles running smoothly. We need to give them a transition effect. So we are going to use transition property.
  3. By default, browsers use linear timing function for transition property, but we can also change it using transition-timing-function. We look at ease-in-out and cubic-bezier function. Sounds cool! Right?

Here is the final CSS

.hand {
 width:50%;
 height:6px;
 background:black;
 position: absolute;
 top:50%;
 transform-origin: 100%;
 transform: rotate(90deg);
 transition: all 0.05s;
 transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
}

Now, turning to JavaScript, here is what we needed to:

  1. Get the HTML elements of clock’s hour, minute and second.
  2. Create a new function which does the following:
    1. Create a new Date() object.
    2. Get the hour, minute, and second from the object.
    3. Calculate the angles by which the hands of the clock are needed to rotate.
    4. Apply those angles to the hands of the clock.
  3. Repeat this function after every second using setInterval function.

Here is the final JS code

const secondHand = document.querySelector('.second-hand');
const minsHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');

setInterval( () => {
 const now = new Date();

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

 const mins = now.getMinutes();
 const minsDegrees = ((mins / 60) * 360) + ((seconds/60)*6) + 90;
 minsHand.style.transform = `rotate(${minsDegrees}deg)`;

 const hour = now.getHours();
 const hourDegrees = ((hour / 12) * 360) + ((mins/60)*30) + 90;
 hourHand.style.transform = `rotate(${hourDegrees}deg)`;
}, 1000 );

Finally, feel free to reach out to me on Twitter @mrasharirfan or comment below this post.

Leave a Reply

Your email address will not be published. Required fields are marked *