JavaScript tutorial-JavaScript Clock


JavaScript Clock

In this example, you will learn to show a clock using JavaScript code. To show a clock that displays the current hour, minute, and second on the current page, you will need to use the JavaScript Date object and Timer. The Date object is used to get the current hour, minute, and second to be displayed. By using the JavaScript Date object alone you can't have a clock that updates every second. Therefore, you need to use the JavaScript timer. In the JavaScript example code below, we use the JavaScript timer to update the time every second(or 1000 milliseconds). Every second the function updateclick() is called and the time is updated. The Date object curdate is created in this function to make sure that you can pick up the current hour, minute, and second. The current hour, minute, and second will be assigned to the dive(mydiv) to display. The function load() is  used to format the div tag and to set the timer when the page loads. This function needs to be put in the onload event of the page.

 

<html>
<head>
<title>JavaScript clock</title>
<script language="JavaScript" type="text/javascript">
var timerID;


function load()
{
document.getElementById("mydiv").style.backgroundColor="00FFBB";
document.getElementById("mydiv").style.width="50px";
document.getElementById("mydiv").style.color="000000";
timerID = setInterval("updateclock()",1000);
}

function updateclock(){
var curdate=new Date();
document.getElementById("mydiv").innerHTML=curdate.getHours()+":"+curdate.getMinutes()+":"+curdate.getSeconds();

}
</script>
</head>
<body language = JavaScript onload="load()">
<div id="mydiv"></div>
</body>
</html>




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.