<div class="clock">
<div class="seconds hand"></div>
<div class="minutes hand"></div>
<div class="hours hand"></div>
</div>
<p><strong id="time-outlet"></strong></p>
:root {
--h-rotation: 0deg;
--m-rotation: 0deg;
--s-rotation: 0deg;
--bg-color: #afe9e5;
--h-color: #292f36;
--m-color: #292f36;
--s-color: #ff6b6b;
--clocl-color: #fff;
--clock-radius: 14em;
}
body {
background-color: var(--bg-color);
display: flex;
flex-direction: column;
}
p {
text-align: center;
font-family: monospace;
font-size: 1.5em;
}
.clock {
align-self: center;
background-color: var(--clocl-color);
height: var(--clock-radius);
width: var(--clock-radius);
border-radius: 50%;
position: relative;
border: 4px solid black;
}
.hand {
height: 43%;
width: 2px;
position: absolute;
bottom: 50%;
right: 50%;
transform-origin: bottom;
border-radius: 2px;
}
.hours {
height: 30%;
background-color: var(--h-color);
transform: rotate(var(--h-rotation));
}
.minutes {
height: 35%;
background-color: var(--m-color);
transform: rotate(var(--m-rotation));
}
.seconds {
background-color: var(--s-color);
transform: rotate(var(--s-rotation));
}
/*
* https://frontendeval.com/questions/analog-clock
*
* Create an analog clock with hour, minute, and second hands. Each of the hands should be accurate to the browser's local timezone and update once per second.
*/
const initClock = () => {
setInterval(() => updateTime(), 1000);
};
const timeOutlet = document.getElementById("time-outlet");
const clock = document.querySelector(".clock");
const root = document.querySelector(":root");
const updateTime = () => {
const [h, m, s] = [
new Date().getHours(),
new Date().getMinutes(),
new Date().getSeconds()
];
root.style.setProperty(`--h-rotation`, `${(h % 12) * 30}deg`);
root.style.setProperty(`--m-rotation`, `${(m % 60) * 6}deg`);
root.style.setProperty(`--s-rotation`, `${(s % 60) * 6}deg`);
timeOutlet.innerHTML = `${h}:${m}:${s}`;
clock.setAttribute("aria-label", `The time is: ${h}:${m}`);
};
initClock();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.