Create Clock in JavaScript Step by Step (2024)

create clock

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.

				
					<svg xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" stroke-width="1" viewBox="0 0 16 16">
	<circle id="marker" r="0.5" cx="8" cy="1" />
	<use href="#marker" style="--minute: 5" />
	<use href="#marker" style="--minute: 10" />
	<use href="#marker" style="--minute: 15" />
	<use href="#marker" style="--minute: 20" />
	<use href="#marker" style="--minute: 25" />
	<use href="#marker" style="--minute: 30" />
	<use href="#marker" style="--minute: 35" />
	<use href="#marker" style="--minute: 40" />
	<use href="#marker" style="--minute: 45" />
	<use href="#marker" style="--minute: 50" />
	<use href="#marker" style="--minute: 55" />
	<path class="minutes" d="M8 1v7" />
	<path class="hours" d="M8 3v5" />
	<path class="seconds" d="M8 1v7" />
</svg>
				
			

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

create clock

Watch Some Other Topics

Home

Leave a Reply

Your email address will not be published. Required fields are marked *