DEV Community

Umapreethi Santhanakrishnan
Umapreethi Santhanakrishnan

Posted on

Javascript , CSS Clock

Creating Html and Css for Clock

  • Create a div for clock and create three div for the hour, minute and second hand.
 <div class="body">
        <div class="clock">
            <div class="hand hour"></div>
            <div class="hand min"></div>
            <div class="hand sec"></div>
Enter fullscreen mode Exit fullscreen mode
  • Use CSS to Create the Clock background
.clock {
    max-width: 500px;
    border: 3px solid white;
    margin: 0px auto;
    margin-top: 100px;
    height: 500px;
    border-radius: 50%;
    position: relative;
Enter fullscreen mode Exit fullscreen mode
  • Use CSS to create the three hour, minute and second hand
.hand {
    width: 50%;
    background-color: #fff;
    position: absolute;
    transform: rotate(90deg);
    transform-origin: 100%;
    transition: all 0.05s;
    transition-timing-function: cubic-bezier(0.1,2.7,0.58,1);
Enter fullscreen mode Exit fullscreen mode

Check transition property for more information.

Js Code

  • First select the second hand to make process. new date() function will give the current date with time. getSeconds() function will give the current seconds, we have to convert it to the degree, once it is converted apply it to the hand using css. Follow the same procedure for minute hand and hour hand. Use setInterval to call the function every 1ms.
const secondHand = document.querySelector(".sec");
const minuteHand = document.querySelector(".min");
const hourHand =  document.querySelector(".hour");

function setDate(){
    const now = new Date();
    const seconds = now.getSeconds();

    const secondDeg = ((seconds / 60) * 360) + 90; = `rotate(${secondDeg}deg)`;

    // minutes
    const minute = now.getMinutes();
    const minDeg = ((minute / 60) * 360) + 90; = `rotate(${minDeg}deg)`;

    // hours
    const hour = now.getHours();
    const hourDeg = ((hour / 12) * 360) + 90; = `rotate(${hourDeg}deg)`;
setInterval(setDate, 1000);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)