Javascript Analog Clock

Web Design & Web Development

Demo

Sponsored links

 

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Javascript Analog Clock</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="clock.js"></script>
  </head>
  <body>
    <div id="container">
      <div class="clock">
        <div id="hours"></div>
        <div id="minutes"></div>
        <div id="seconds"></div>
      </div>
      <h1>Javascript Analog Clock</h1>
    </div>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  background-color: #112c4f;
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  padding: 30px 15px;
}
.clock {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-image: url(clock.svg);
  background-position: center;
  background-size: 200px 200px;
  background-repeat: no-repeat;
}
.clock::before {
  position: absolute;
  top: 95px;
  left: 95px;
  z-index: 999;
  width: 9px;
  height: 9px;
  border-radius: 50%;
  background-color: #3d3935;
  content: "";
}
#hours {
  position: absolute;
  top: 40px;
  left: 97.5px;
  transform-origin: bottom;
  width: 5px;
  height: 60px;
  background-color: #112c4f;
}
#minutes {
  position: absolute;
  top: 20px;
  left: 98.5px;
  transform-origin: bottom;
  width: 3px;
  height: 80px;
  background-color: #e9c277;
}
#seconds {
  position: absolute;
  top: 10px;
  left: 99.5px;
  transform-origin: 0 90px;
  width: 1px;
  height: 110px;
  background-color: #d73659;
}
h1 {
  margin: 30px 0 0;
  color: #fff;
  font-size: 2.5rem;
  letter-spacing: 1px;
  text-align: center;
}
@media screen and (max-width: 480px) {
  #container {
    height: auto;
  }
  h1 {
    font-size: 2rem;
  }
}

Javascript

function startClock() {
  const hr = document.getElementById("hours");
  const min = document.getElementById("minutes");
  const sec = document.getElementById("seconds");

  let date = new Date();
  let hh = date.getHours();
  if(hh >= 12) {
    hh = hh - 12;
  }
  let mm = date.getMinutes();
  let ss = date.getSeconds();

  hr.style.transform = "rotateZ(" + (hh*30 + mm*0.5) + "deg)";
  min.style.transform = "rotateZ(" + mm*6 + "deg)";
  sec.style.transform = "rotateZ(" + ss*6 + "deg)";
}

window.addEventListener('load', (event) => {
  setInterval(startClock, 1000);
});