Digital Clock Project using Java Script and HTML for School Students
Create file named digitalclock.html. Edit it using any text editor and paste the following code. The output will be the digital clock shown in thumbnail.
<center>
<div id=”clock”></div>
<button onClick=”startClock()”>Start Clock</button>
<button onClick=”stopClock()”>Stop Clock</button>
</center>
<script>
function startClock(){
var date = new Date();var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var session = “AM”;if(hour>12){
hour = hour – 12;
session = “PM”;
}if(hour<10) hour = “0”+hour ;
if(min<10) min = “0”+min;
if(sec<10) sec = “0”+sec;
if(hour == 0) hour = 12;document.getElementById(“clock”).innerText= hour+”:”+min+”:”+sec+” “+session;
cleartimeout = setTimeout(startClock,1000);
}
function stopClock(){
clearTimeout(cleartimeout);
}
</script>
<style>
body{
background-color:black;
background:radial-gradient(darkcyan 0%,black 80%)
}
#clock{
color:cyan;
font-family:stencil;
font-size:4em;
height:100px;
margin-top:250px;
}
</style>
Now we will analyse the whole program line by line.
First five lines are HTML codes.
center tag : All the elements contained with in this tag will be aligned to the middle of the web page. CSS text-align:center; can also be used for the same purpose.
div tag : This tag is used to mention a division or section in a HTML document. Normally this tag is used as container for other HTML elements. CSS and JavaScript can access it by it’s tag name or it’s class or id property. That why we used id property on the first div element.
button tag : It can be used to create a clickable button on web page.
onClick event attribute: onClick event attribute added to button tag. When user clicks on a button by mouse, the script with in double quotes mentioned in the onClick event will be executed. In this case we have used a javascript function. The first button in our program will start the clock and the second button will stop the clock.
script tag : This tag is used to write java script codes with in it or can be point to an external java script file through src attribute. In our program we are writing java script code with in it.
function startClock() : To perform a particular function we can group a number of java script statements in a single group. This can be done using function keyword. function keyword follows function name and open and closing parenthesis. In our case the function name is startClock. With in the parenthesis we can specify different arguments. But in our case we are not using any argument in this case. The naming rule for a function is same as naming rule for a variable. Means only letters, digits, underscores and dollar signs can be used in a function name.
The group of statements written inside a function block will be executed when we call the function name. In this example this function is called from start clock button’s onClick event.
var : This keyword can be used to declare a local variable in javaScript. The variables can also be created without using the var keyword. But in this case we have to initialise it at the same time. This type of variable will also be a global variable, irrespective of the block in which it is declared and initialised.
In this program we have declared the cleartimeout variable without var keyword and directly initialising it with = operator to make it global so that we can use it in another function stopClock(). Means the variable is declared in startClock() function and we used it in stopClock() function.
Variables declared using var keyword can be initialised later. But it should assigned any value before using. By default the variables declared with var keyword has assigned undefined value to it. JavaScript variables are loosely typed variables, means any type of value can be assigned to them after declaration. But in case programming languages line C and Java, at the time of declaration we have to specify the type of value that variable will contain. They are called strongly typed variables.
new Date() : This can be used to create a new date object in JavaScript. New date object can be created in 4 different ways in java script as below :
- new Date() : it creates a new date object and assigns current date and time.
- new Date(year, month, day, hours, minutes, seconds, milliseconds) : creates a new date object with specified parameters.
- new Date(miliseconds) : creates a new date object with specified parameter.
- new Date(date string) : example : new Date(“May 28, 2020 13:49:00”);
In our program we have created a new date object with current date and time and assigned it to variable date.
JavaScript date methods
To pull a specific information like only year, month, hour we can use different methods. Some methods are discussed below.
Method | Description |
getDate | returns the date as a number from 1 to 31 |
getMonth | returns the month as a number from o to 11. Means 0 for January, 1 for February and so on. |
getYear | subtracts 1900 from the year of date and returns the result |
getFullYear | returns the year of date in YYYY format |
getHours | returns the hour as a number from 0 to 23 |
getMinutes | returns the minute as a number from 0 to 59 |
getSeconds | returns the seconds as a number from 0 to 59 |
getMiliseconds | returns the milliseconds as a number from 0 to 999. Note that 1000 milliseconds = 1 second |
getDay | get the day as a number from 0 to 6. we got 0 means sunday, 1 means monday and so on. |
In this program using getHours() method we have extracted only hour and assigned it to the variable hour. Similarly using getMinutes() method we have extracted only minutes and assigned it to the variable min. Similarly using getSeconds() method we have extracted only seconds and assigned it to the variable sec.
Checking Current Session of Time
Now we have to check the current session is AM or PM, as we want to present the time in 12 Hours format. In our program we declared a new variable session and assigned AM to it. Now we will check weather the value stored in hour variable is greater then 12. If it is greater then 12 then we will assign PM to session variable and subtract 12 from hour to make it 12 hour format. For this purpose we have used if statement as below :
if(hour>12){
hour = hour – 12;
session = “PM”;
}
JavaScript if statement
Syntax : if(condition){ Block of statements to be executed if condition is true}
JavaScript if statement evaluates the condition specified with in the parenthesis. if the condition specified is true then it evaluates the block of statements present with in the curly braces.
Adding zero to the left of single digit hour, minute and second
Single digit hour, minute and seconds will not look good. So we added extra zero to its left using if statement. The statements used for this purpose are repeated below :
if(hour<10) hour = “0”+hour ;
if(min<10) min = “0”+min;
if(sec<10) sec = “0”+sec;
Midnight should display as 12 AM
If our current time is midnight it will assign 0 to hour. But as per our program requirement it should display 12 AM. for this purpose we used the below if statement.
if(hour == 0) hour = 12;
Time to display the JavaScript digital clock on webpage
Now its the time to access the HTML div element, which has id clock and display our hour, minute, second and session there. This can be done using the below statement. = is the assignment operator. It assigns value of right hand side operand to left hand side operand, as it’s a right to left operator.
document.getElementById(“clock”).innerText= hour+”:”+min+”:”+sec+” “+session;
Watch above statement, left hand side we are accessing the div with id clock and assigning right hand side operand to its .innerText property. The details about HTML DOM innerText property is mentioned below.
Right hand side operand of above statement concatenates hour, mininute, second and session with + operator and a colon symbol is also concatenated to give it proper look.
HTML DOM innerText Property
This property can be used to set or get the text content of the specified node. The textContent property also does the same work except the below mentioned.
- innerText does not return the text content of SCRIPT and STYLE tags.
- innerText will not return the text content which are hidden using CSS.
JavaScript Window setTimeout method
This method can be used to call a specific function or evaluate a specific operation after a specified number of milliseconds.
This function executes only once. If we want to repeat it for a number of times then we have to use setInterval method.
But it our program it is executing repeatedly because we have used it with in function itself. So the function startClock becomes recursive and repeats after each 1000 milliseconds, means 1 second. So it displays new calculated time after each one seconds.
JavaScript Window clearTimeout method
This method is used to clear a timer set with the setTimeout method. In our program we stored the setTimeout to a variable cleartimeout. Observe here we have used all small letters here, so it has different meaning then clearTimeout method. You can use any other variable name also. Then using the below statement we have cleared the variable.
clearTimeout(cleartimeout);
To watch the complete video tutorial of this project enroll on course : digital clock project using JavaScript for school students.
Those who have purchased the subscription pack (Monthly, Quarterly, Half-yearly or Yearly) can watch this for free by downloading. Click here to know more about subscription packs of Subrat Sir’s courses.
Click here to download the recorded video tutorial in Hindi Language
To enroll to the life time valid step by step explained java course i am teaching on Udemy click here.
To enroll to the life time valid step by step explained C programming course i am teaching on Udemy Click here.
You must log in to post a comment.