Creating Html and Css for Clock
- Create a
div
for clock and create threediv
for the hour, minute and second hand.
HTML
<div class="body">
<h1>Clock</h1>
<div class="clock">
<div class="hand hour"></div>
<div class="hand min"></div>
<div class="hand sec"></div>
</div>
</div>
- 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;
}
- Use CSS to create the three hour, minute and second hand
.hand {
width: 50%;
height:4px;
margin:5px;
background-color: #fff;
position: absolute;
top:50%;
transform: rotate(90deg);
transform-origin: 100%;
transition: all 0.05s;
transition-timing-function: cubic-bezier(0.1,2.7,0.58,1);
}
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 thedegree
, once it is converted apply it to the hand using css. Follow the same procedure for minute hand and hour hand. UsesetInterval
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();
//seconds
const secondDeg = ((seconds / 60) * 360) + 90;
secondHand.style.transform = `rotate(${secondDeg}deg)`;
// minutes
const minute = now.getMinutes();
const minDeg = ((minute / 60) * 360) + 90;
minuteHand.style.transform = `rotate(${minDeg}deg)`;
// hours
const hour = now.getHours();
const hourDeg = ((hour / 12) * 360) + 90;
hourHand.style.transform = `rotate(${hourDeg}deg)`;
}
setInterval(setDate, 1000);
Top comments (0)