JavaScript code for creating a simple digital clock
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
//to add a zero in front of numbers<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('clock').innerHTML=h+":"+m+":"+s
t=setTimeout('startTime()', 500)
}
function checkTime(i)
{
if (i<10)
{ i="0" + i}
return i
}
window.onload=startTime;
</script>
<div id="clock" style="font-size:35px;color:#00aaff;text-shadow:2px 2px 2px blue;
border:3px groove blue;background-color:#aaffaa; width:195px; height:40px"></div>
#clock{
font-size:35px;
color:#00aaff;
text-shadow:2px 2px 2px blue;
border:3px groove blue;
background-color:#aaffaa;
width:195px;
height:40px;
}
JavaScript code for creating a digital clock with AM or PM
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
var ap="AM";
//to add AM or PM after time
if(h>11) ap="PM";
if(h>12) h=h-12;
if(h==0) h=12;
//to add a zero in front of numbers<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('clock').innerHTML=h+":"+m+":"+s+" "+ap
t=setTimeout('startTime()', 500)
}
function checkTime(i)
{
if (i<10)
{ i="0" + i}
return i
}
window.onload=startTime;
</script>
<div id="clock" style="font-size:35px;color:#00aaff;text-shadow:2px 2px 2px blue;
border:3px groove blue;background-color:#aaffaa; width:195px; height:40px"></div>
In the above code, variable ap is added to make the clock 12 hour format and to add "AM" or "PM" after the time and added this variable at innerHTML of clock element.
Preview of digital clock created with JavaScript
Related Posts
- How to Detect Visitor's Browser Using JavaScript?
- What are the Different Ways to Redirect Page in JavaScript?
- How To Create Simple Image Slideshow Using JavaScript ?
- How to Create Simple JavaScript Fade Effect Animation?
- Image Slideshow with Navigation Buttons Using Javascript
- How to Create JavaScript Image Slideshow with Links
- Simple JavaScript Fade Effect Animation Using Jquery
- How to Create Simple JavaScript Fade Effect Animation?
إرسال تعليق
Click to see the code!
To insert emoticon you must added at least one space before the code.