Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Murtaja Ziad
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>
Enter fullscreen modeExit fullscreen mode

Then, put ah2 with threespan with the IDhours,minutes andseconds..

<h2><spanid="hours">00</span> :<spanid="minutes">00</span> :<spanid="seconds">00</span></h2>
Enter fullscreen modeExit fullscreen mode

Now, it will look like this..how to create a clock using javascript 1

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;}
Enter fullscreen modeExit fullscreen mode

It will look like this..how to create a clock using javascript 2

After that, create the main function which will get the time and put it into thespans

// 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);
Enter fullscreen modeExit fullscreen mode

and yeah, now it’s working..how to create a clock using javascript 3

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A Full-Stack Web Developer.
  • Location
    Baghdad, Iraq
  • Joined

More fromMurtaja Ziad

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp