Murtaja Ziad
Posted on • Originally published atblog.murtajaziad.xyz on
How to create a clock using JavaScript?
In the beginning, create a new HTML, CSS & JavaScript file..
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Clock using JavaScript</title><linkrel="stylesheet"href="style.css"/><scriptsrc="app.js"defer></script></head><body></body></html>
Then, put ah2
with threespan
with the IDhours
,minutes
andseconds
..
<h2><spanid="hours">00</span> :<spanid="minutes">00</span> :<spanid="seconds">00</span></h2>
Add some basic styling with a background..
body{padding:0;margin:0;box-sizing:border-box;min-height:100vh;background-image:url("https://images.unsplash.com/photo-1605364441002-c1dbf7d9c7f1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&q=100");background-repeat:no-repeat;background-position:center40%;display:flex;align-items:center;justify-content:center;}h2{font-size:7rem;color:white;}
After that, create the main function which will get the time and put it into thespan
s
// Define the hours, minutes & seconds elements.consthoursEl=document.getElementById("hours");constminutesEl=document.getElementById("minutes");constsecondsEl=document.getElementById("seconds");functionmain(){consttotalSeconds=newDate().getTime()/1000;consthours=Math.floor(totalSeconds/3600)%24;constminutes=Math.floor(totalSeconds/60)%60;constseconds=Math.floor(totalSeconds)%60;hoursEl.innerText=formatTime(hours);minutesEl.innerText=formatTime(minutes);secondsEl.innerText=formatTime(seconds);}// Format the time by adding 0 before the time if it's less than 10..functionformatTime(time){returntime<10?`0${time}`:time;}// Initial call.main();// Call the function every second.setInterval(main,1000);
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse