Create a Analog Clock with JavaScript, HTML and SASS
Today we are going to learn how to make a simple analog clock using Javascript. The main goal of this project is how to implement the Date() object in JavaScript.
Features :
- Show current time.
- Display the time in the analog clock UI.
- Light and dark mode toggle button available.
How will we do this?
- First we give id to hour, minutes and seconds in our HTML code.
- After that we need to creat a function that runs every one seconds.
- Then we will take reference from the hour, minutes, and seconds by their ID respectively.
let hr = document.getElementById('hr'); let mn = document.getElementById('mn'); let se = document.getElementById('se');- Now we will use Date() object to get the current hour, minutes, and seconds that we need to make up our clock.
let day = new Date(); let Hr = day.getHours(); let Mn = day.getMinutes(); let Se = day.getSeconds();- Now we have to remember this is a analog clock So, we want to convert the rotation of the handle of the clock into 360 degrees.
let degree = 6; let hr = document.getElementById('hr'); let mn = document.getElementById('mn'); let se = document.getElementById('se'); setInterval(() => { let day = new Date(); let Hr = day.getHours()*30; let Mn = day.getMinutes()*degree; let Se = day.getSeconds()*degree; hr.style.transform = `rotatez(${Hr+(Mn/12)}deg)` mn.style.transform = `rotatez(${Mn}deg)` se.style.transform = `rotatez(${Se}deg)` }, 1000);- The setInterval() function runs every 1000 milliseconds. So it means the Date() onject runs every seconds and then updates out HTML Code as the value calculated.
Project Files
| .. | ||
| This directory is empty. | ||