Create Clock In Javascript
Here, we create clock using HTML, CSS and JS.
Project Folder Structure
Before we start coding we take a look at the project folder structure. We start by creating a folder called – “Create Clock” Inside this folder, we have 3 files. Create these files like below:
- index.html
- style.css
- script.js
HTML
We create clock using HTML code. Copy the code below and paste it into your index.html file.
CSS
We create clock using CSS code. Copy the code below and paste it into your style.css file.
:root {
color-scheme: light dark;
}
@keyframes rotate {
to {
transform: rotate(360deg);
}
}
body {
background-color: light-dark(#def, #123);
box-sizing: border-box;
margin: 0;
}
svg {
box-sizing: border-box;
display: flex;
height: 100vh;
padding: 5vmin;
width: 100vw;
}
path,
use {
transform-origin: 8px;
}
use {
transform: rotate(calc(var(--minute, 0) * 6deg));
}
path {
animation-delay: calc(var(--day-seconds, 0) * -1s);
animation-duration: 60s;
animation-iteration-count: infinite;
animation-name: rotate;
animation-timing-function: steps(60);
}
.minutes {
animation-duration: 3600s;
stroke: light-dark(#123, #def);
}
.hours {
animation-duration: 43200s;
stroke: #678;
}
.seconds {
stroke: #e06;
stroke-width: 0.5px;
}
#marker {
fill: light-dark(#123, #def);
}
JS
Finally, we add functionality in clock using JavaScript. Copy the code below and paste it into your script.js file.
((date) =>
document
.querySelector("svg")
.style.setProperty(
"--day-seconds",
date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()
))(new Date());
CODEPEN
Watch Some Other Topics