Adding a digital clock to your website isn't hard. And I'm here to teach you a simple way to create an hours-minutes-seconds clock. Just follow these steps.
First, in the <body> section of the webpage, we want a tag that will display the clock. The clock could be put somewhere like the sidebar, so you want your tag to go there. Also, the tag should have the "id" attribute so we can access it using JavaScript.
Here's an example:
--
<div id="clock"></div>
--
We should also spice up the clock with some CSS.
Here's another example, with the CSS:
--
<div id="clock" style="width:100px;height:30px;background-color:#A1E68E;color:#000000;text-align:center;font-size:20px;border-style:solid;border-width:2px;border-color:#2F8A16;"></div>
--
Second, in the <script> tag, we must now create a function and then an interval that will repeat the function. The function will get the hours, minutes, and seconds, and add the information to the "div" tag, while the interval will repeat the function every second.
--
function clock(){
var c=new Date();
var h=c.getHours();
var m=c.getMinutes();
var s=c.getSeconds();
document.getElementById("clock").innerHTML=h+":"+m+":"+s;
}
setInterval("clock()",1000);
--Here's an example:
--
<div id="clock"></div>
--
We should also spice up the clock with some CSS.
Here's another example, with the CSS:
--
<div id="clock" style="width:100px;height:30px;background-color:#A1E68E;color:#000000;text-align:center;font-size:20px;border-style:solid;border-width:2px;border-color:#2F8A16;"></div>
--
Second, in the <script> tag, we must now create a function and then an interval that will repeat the function. The function will get the hours, minutes, and seconds, and add the information to the "div" tag, while the interval will repeat the function every second.
--
function clock(){
var c=new Date();
var h=c.getHours();
var m=c.getMinutes();
var s=c.getSeconds();
document.getElementById("clock").innerHTML=h+":"+m+":"+s;
}
setInterval("clock()",1000);
The result of this code:
No comments:
Post a Comment
Please keep your comments appropriate.