Create a simple Digital Clock for Your website with Javascript.

Published on Oct. 15, 2020, 9:14 a.m.



You have to create a unordered list using <ul> and</ul> tags in your HTML file. And inside it include 3 <li> elements for Hours, Minutes and Seconds .


ul >
<li id='hours'></li>
<li id = 'minutes'></li>
<li id ='seconds'></li>
</ul>

Write The Script With Javascript

Then you can place your script inside head tags.

<script>
function newfunc() {
a = new Date();
day ="AM"
hours = a.getHours();
if (hours > 12){
hours = hours -12;
day = 'PM'
}
else{
}
document.getElementById("hours").innerHTML = ("0"+hours).slice(-2)+':';
document.getElementById("minutes").innerHTML = ("0"+a.getMinutes()).slice(-2)+':';
document.getElementById("seconds").innerHTML = ("0"+a.getSeconds()).slice(-2)+"&nbsp;"+day;


}
setInterval(newfunc,1000);


Stylise the Unordered List

Add a <style> tag to stylise the <li> elements

<style>
li {
display: inline-block;
font-size: xx-large;
}

</style> 

and add a inline CSS to stylise the Unordered list

<ul style="float:right; ">
<li>Your Current Time &nbsp;</li>
<li id='hours'></li>
<li id = 'minutes'></li>
<li id ='seconds'></li>
</ul>


Then It Looks like this


You Can Simply clone my clock from github

Happy Coding...