Javascript Lesson For Vii and Viii
Javascript Lesson For Vii and Viii
1|Page
Table of Contents
Lesson 1 : HTML in Nutshell ............................................................................................ 5
1.1 HTML & JavaScript Editors ............................................................................................................. 5
1.1.1 How to open Notepad ............................................................................................................. 5
1.1.2 How to create a new HTML document using Notepad. .............................................. 7
1.1.3 How to open an existing HTML file in Notepad: ............................................................ 9
1.1.4 How to open an HTML file in a web browser: ............................................................... 10
1.2 Basic of HTML File ........................................................................................................................... 12
1.3 Title and Headings .......................................................................................................................... 13
1.4 Paragraphs ......................................................................................................................................... 14
1.5 Buttons ............................................................................................................................................... 15
2|Page
4.2.3 Logical Operators .................................................................................................................... 37
4.2.4 Assignment Operators ........................................................................................................... 38
3|Page
Lesson 8 : Clock & Counter ............................................................................................. 75
8.1 Date object ......................................................................................................................................... 75
8.2 setTimeout & setTimeInterval ..................................................................................................... 76
8.3 Project 1 : Clock ................................................................................................................................ 78
8.4 Project 2 : Counter........................................................................................................................... 79
4|Page
Lesson 1 : HTML in Nutshell
The easiest way to develop a web page is by using Notepad. It is a very simple text
editor and easily available. It can not only be used to create an HTML document, but
also to modify an existing HTML document.
1. Click the Start button, select All Apps, and then navigate to Windows Accessories.
Look for a notepad and click on the icon of Notepad.
5|Page
2. Press Windows (logo)+R, type “notepad” and then select OK as shown below.
6|Page
4. Right-click on a blank area, select new from the context menu. Then click on the
“Text Document”.
7|Page
3. Then select “Save As…” from the dropdown menu. After that, Save As Window
will open.
4. Navigate and select the desired location for saving the HTML document. Next,
click the “Save as type” which is located at the bottom of the window. By default
setting, the “Text documents (*.txt)” has already been chosen. Click it and it
prompts a dropdown as shown below.
8|Page
5. Now, click “All Files” from the drop-down menu. This allows a text file to save as
an HTML document.
6. In File name: textbox, enter a desired name of the file with extension “.html” and
click Save. For example, the name of the file can be “helloWorld.html” as shown
below.
2. Select the file and right-click on it. Then choose “Open with” from the context menu.
After that, click Notepad as shown below.
9|Page
3. Subsequently, the selected file will open in Notepad and it can be edited.
1. Navigate to the location of an HTML file with the help of Windows Explorer and
simply double click on it. Then, the file will open in the default web browser.
10 | P a g e
b. Click “Open File…” in the drop-down menu and immediately afterwards an
Open File window pops up. Navigate to the location of the HTML file then
select it and click Open as shown below.
11 | P a g e
1.2 Basic of HTML File
HTML uses a standardized system of markup tags to control various aspects on web
pages such as the font, colour, hyperlink, etc. The first question arises here, what are
markup tags? They are hidden keywords within web pages, which direct web browsers
to format and arrange contents on web pages. The majority of tags work in pairs, each
pair comprises one opening tag and one closing tag. For example, <html> and </html>,
where <html> is an opening tag and </html> is a closing tag.
Irrespective of the contents of web pages, a few markup tags are common and
compulsory across all HTML documents. These are listed below with a brief description.
<!Document html> : It defines the type of the document and its HTML version. It
helps web browsers to identify the document properly. Therefore, the presence
of this markup tag at the beginning of all HTML documents only once.
<html> and </html> : All HTML documents begin with <html> and end with
</html>. These tags comprise an entire HTML document within them.
Furthermore, an entire document which is closed inside them is divided into two
parts: head and body.
To understand the above markup tags, study the following example thoroughly.
<!DOCUMENT html>
<html>
<head>
<title>This is the title of the web page.</title>
</head>
<body>
<p>My first paragraph.</p>
</body>
</html>
12 | P a g e
1.3 Title and Headings
These tags are used to show what a web page is all about. The title tags are used inside
the head of a web page and heading tags are used in the body of web pages. Title tag
sets the title in the toolbar of a web browser, whereas headings tags set headings of a
web page.
<!DOCTYPE html>
<html>
<head>
<title>This is title of the page</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
13 | P a g e
Output:
1.4 Paragraphs
With the <p></p> tag, the text content on a web page can be arranged into different
paragraphs. A paragraph on a web page always begins with a new line and by default
some space is added before and after a paragraph. Each paragraph begins with an
opening tag <p> and ends with a closing tag </p>. For example,
<!DOCTYPE html>
<html>
<head>
<title>An Example Paragraph</title>
</head>
<body>
<p>This is an example of paragraph to understand that how a paragraph is
seen on a web page.</p>
<p>This is a paragraph which is used to arrange text on a web page.</p>
<p>A space is added automatically before and after of a paragraph on a
web.</p>
</body>
</html>
14 | P a g e
Output:
1.5 Buttons
A button can be added to a web page very easily. A button can have many uses such as
connecting two web pages, playing multimedia, etc. Let’s see how to create a button on
a web page.
<!DOCTYPE html>
<html>
<head>
<title>HTML Button</title>
</head>
<body>
<form action="">
<input type="button" value="Click!">
</form>
</body>
</html>
Output:
There is one more way by which a button can be placed on a web page using <button>
tag. For example,
<!DOCTYPE html>
<html>
<head>
<title>HTML Button</title>
</head>
<body>
15 | P a g e
<h1>Button Element</h1>
<button>Click!</button>
</body>
</html>
Output:
16 | P a g e
Lesson 2 : Start JavaScript
JavaScript is one of the most powerful and flexible languages for web development. It is
also a very common and lightweight programming language which is used almost in all
websites. Generally, it is used in combination with HTML because it interacts with
various HTML elements of web pages. As a result, web pages become interactive.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript </title>
<script>
//This is the place where all the statements of JavaScript should be written.
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
17 | P a g e
<html>
<head>
<title>JavaScript </title>
</head>
<body>
<script>
//This is the body of the HTML document.
//Make sure all the statement of JavaScript
//should be written within script tags
alert("Hello World!");
</script>
</body>
</html>
18 | P a g e
2. Then, save the file with any name with file extension “.js”.
3. Create a corresponding HTML document with the following code and keep ready
the file location of the “.js” file (Such as “D:\Jscript.js”).
<html>
<head>
<title>JavaScript </title>
<script src="D:\Jscript.js"> </script>
</head>
<body>
</body>
</html>
Paste the path of the “.js file” location in the area which is highlighted with yellow
colour. After that save the HTML file.
4. Now, open this HTML file in a web browser. It shows “Hello World!” text on the
page.
This way one can create and incorporate external JavaScript files in an HTML document.
19 | P a g e
2.2 Selection of HTML elements
As it is already explained, JavaScript is used to add interactivity to web pages. It also
increases the functionality of HTML elements of web pages. To do this, the selection of
HTML elements is the primary requirement. This can be done with the help of an
attribute called the “id” and a JavaScript method or function called the
getElementById("Id_value"). The “id” should be attached to those HTML elements which
are to be selected for upgrades by a JavaScript program. Check the following example
to understand this.
<!DOCTYPE html>
<html>
<head>
<title>Selection of an HTML Element</title>
</head>
<body>
<p>This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<!--Comment: The following paragraph is selected from attribute id.-->
<p id="para">This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<script>
document.getElementById("para").innerHTML="The content of this paragraph
has been changed by JavaScript.";
</script>
</body>
</html>
Output:
20 | P a g e
Similarly, more than one HTML element can be selected with “id”. For example,
<!DOCTYPE html>
<html>
<head>
<title>Selection of HTML Elements</title>
</head>
<body>
<h1>This is an example of the HTML Heading 1</h1>
<p>This is an example of the HTML paragraph.</p>
<h2 id="sr1">This is an example of the HTML heading 2 </h2>
<p>This is an example of the HTML paragraph.</p>
<h3>This is an example of the HTML heading 3</h3>
<!--Comment: The following paragraph is selected from attribute id.-->
<p id="para">This is an example of the HTML paragraph.</p>
<p>This is an example of the HTML paragraph.</p>
<h6 id="sr2"></h6>
<p>This is an example of the HTML paragraph.</p>
<script>
document.getElementById("para").innerHTML="Change Made by JavaScript";
document.getElementById("sr1").innerHTML="Change Made by JavaScript";
document.getElementById("sr2").innerHTML="Change Made by JavaScript";
</script>
</body>
</html>
Output:
21 | P a g e
Lesson 3 : Outputs, Functions and Events
This lesson deals with three fundamental aspects of JavaScript: output display, use of
functions and various events. Understanding of three things is extremely important in
Javascript. This lesson explains them one by one.
Sr.
Methods Description
No.
It is used to show outputs by changing the content
1 innerHTML
of HTML elements.
2 document.write() It shows outputs on a web page.
3 window.alert() It exhibits output inside an alert box.
4 console.log() It displays outputs in the console.
22 | P a g e
2. Output Display Using Document.Write():
<!DOCTYPE html>
<html>
<head>
<title> Output Display Using document.write()</title>
</head>
<body>
<h5>The multiplication of 27 and 7 is given below.</h5>
<script>
document.write(27*7);
</script>
</body>
</html>
Output:
23 | P a g e
Output:
Note: It is recommended that all the JavaScript instruction should be ended with a
semicolon, though it is not compulsory.
24 | P a g e
programmer wants. It provides a feature of code reusability in programming languages.
One more important thing about a function is that it does not execute unless it is called.
One can call a function anytime.
After this, the first question that arises here is how one can create or define a function in
JavaScript. Four points are required to declare a function in the JavaScript.
1. The name of a function is always followed by the keyword “function”.
2. After that place open and close parenthesis or round brackets “( )”
3. Then comes, the open and close braces i.e. curly brackets “{ }”
4. All JavaScript statements are placed inside the curly brackets
The second question that arises here is how to call a function. In a very simple way, only
by mentioning the name of the function along with open and close parenthesis, the
function can be called.
</head>
<body>
</body>
</html>
25 | P a g e
Output:
3.3 Events
An action that happens and takes place in the system is called the event. It can also be
perceived as a signal which indicates something has happened or has been initiated. In
the event-based programming paradigm, the flow of execution in a program is
determined by the occurrence of various events in the system. For example, the click of
a button, a key pressed, movement of a mouse, loading of a web page, selection of an
option, a message from another program, etc.
Events are also essential for web development. JavaScript interacts with HTML and a big
part of this interaction is based on events that occur when a user or a browser
manipulates a page. Codes of JavaScript can be executed when an HTML event occurs.
An HTML event can be something which either a user does or a browser does. There are
numerous HTML events available and some of them are mentioned below.
26 | P a g e
Form/ onreset when a reset button is clicked
input onsubmit When a form is submitted
onfocus When an input element is focused by a user
onselect When an input text is selected by a user
onblur When an input field is left by a user.
onchange When the content of an input field is changed e.g.
an option is selected in the drop-down menu.
Where the element can be any HTML element, event is the attribute of HTML
elements. The event can be anything which is mentioned in the second column of the
above table. JavaScript statements can be placed inside the double quotes which are
required to be executed as an event is triggered. For example,
<button onclick="document.getElementById('hd1').innerHTML='Hello'">Click</button>
1. Click event:
<!DOCTYPE html>
<html>
<head>
<title>Click Event</title>
</head>
<body>
<button onclick="this.innerHTML='Clicked!'">Click Me!</button>
</body>
</html>
Output:
Before the Event take place After the the event taken place
27 | P a g e
2. Double Click Event:
<!DOCTYPE html>
<html>
<head>
<title>Click and double Click Events</title>
</head>
<body>
<button ondblclick="this.innerHTML='Double Clicked!'">Click Me!</button>
</body>
</html>
<html>
<head>
<title>Mouse over and Mouse out Events</title>
</head>
<body>
<h1 onmouseover="style.color='green'" onmouseout="style.color='Blue'">
Move the cursor of the mouse over this text.
</h1>
</body>
</html>
4. Load Event
<!DOCTYPE html>
<html>
<head>
<title>Load Event</title>
<script>
function doStuff() {
alert("The page has been loaded!");
document.getElementById("hd2").innerHTML="This text is also loaded along
with the page.";
}
</script>
</head>
<body onload="doStuff()">
<h2 id="hd2"></h2>
</body>
</html>
28 | P a g e
5. Keydown Event
<!DOCTYPE html>
<html>
<head>
<title>Keydown Event</title>
<script>
function doStuff() {
alert("You pressed a key down inside the text box");
document.getElementById("para").innerHTML ="Keep writing your name.";
}
</script>
</head>
<body>
<h3>
Try to Enter your name in the following Text Box
to see how this function works.</h3>
<input type="text" onkeydown="doStuff()">
<p id="para"></p>
</body>
</html>
29 | P a g e
Lesson 4 : Variables and operators
This chapter is about variables and operators of JavaScript. The concept of variables and
operators might be known to students already because they often encounter variables
and operators in mathematical equations such as x+9 where x is a mathematical variable
and plus (+) sign is an operator.
Operators are symbols which represent different computations. The computation can be
of many types such as arithmetical, logical, conditional, etc. However, among them, the
most common one is arithmetical. There are only four arithmetical operations available
which are known to everyone, that is, addition, subtraction, division and multiplication.
4.1 Variables
Variable is the name of a storage location in JavaScript. There are certain rules in
JavaScript to name a variable. They are mentioned as follows.
1. The name of the variable must be started with a letter (a to z or A to z),
underscore (_), or dollar ($) sign.
2. The numbers (0 to 9) can be used in the name after the first letter. It is invalid to
start the name of a variable with a number.
3. The name of a variable should be unique and must not match with another
existing variable in a program.
One more thing about names in JavaScript is that it is case sensitive. The case sensitive
means the uppercase and lowercase letters are considered as different letters. For
example, “Cat” and “cat” are treated as different names. Therefore, variables with such
case sensitivity are also viewed as different variables in JavaScript.
30 | P a g e
4.1.1 Declaration of variables
To declare a variable in JavaScript, commonly a reserved keyword “var” is used. The
name of a variable is succeeded by the keyword. The structure of the syntax in his case
should be the same as follows.
var variableName;
Using the assignment operator “=”, one can store data into a variable. Let us understand
the declaration and initialisation of a variable with the help of the following example.
// declaration of a variable
var message;
The declaration and initialisation of multiple variables are possible in a single line. For
example,
Make a note that a variable in JavaScript can be declared without the keyword “var”.
31 | P a g e
Like all other programming languages, JavaScript also supports the feature of data
types. JavaScript has about seven data types. These data types are categorised into two
categories: primitive and non-primitive. This lesson only talks about primitive data
types. They are as follows.
Data Type Description Declaration and Initialization
+ It is used to add two or more numerical operands such as x+y, 3+5+4, etc.
33 | P a g e
The following example shows how these operators work.
<html>
<head>
<title> Arithmetic Operators</title>
</head>
<body>
<script>
//Declaration and initialization of variables
var x = 57;
var y = 42;
var z = " Total ";
var lb="<br>"
var l ="<hr>"
34 | P a g e
document.write("x**2 : ");
answer = x**2;
document.write(answer);
document.write(lb + lb + lb);
Name of
Operator Description Example
operator
== Is equal to It compares the equality of two operands. (50 ==75) = false
!= Not equal to It compares the inequality of two operands (50!=75) = true
It checks whether an operand on left is
> Greater than (75 > 50) = true
greater than an operand on the right
It checks whether an operand on left is less
< Less than (75 < 50) = false
than an operand on the right
Greater than It checks whether an operand on left is
>= greater than or equal to an operand on the (75 >= 50) = true
or equal to
right
Less than or It checks whether an operand on left is less
<= (75 <=50) = false
equal to than or equal to an operand on the right
35 | P a g e
The following example demonstrates how these operators work.
<html>
<head>
<title> Comparison operators</title>
<script>
/*Declaration and initialization of variables*/
var x= 50, y = 75, lb = "<br>";
document.write("x = " + x + lb +"y = "+ y);
document.write(lb + lb);
/*Equality comparison*/
document.write("(x == y) => ");
answer = ( x == y);
document.write(answer);
document.write(lb + lb);
/*Inequality comparison*/
document.write("(x < y) => ");
answer = (x < y);
document.write(answer);
document.write(lb + lb);
36 | P a g e
document.write(lb + lb);
Name of
Operator Description Example
operator
(10==20) && (20==33) = false
&& And True if both operands are true (50>35) &&(60<75) = true
(23<23)&&(50>45) = false
(10==20) || (20>=33) = false
True if either one out of two
|| Or (10<20) || (20 != 33) = true
operands is true
(45>=75) || (20<33) = true
!(20==20) = false
! Not True if an operand is not true !(10>20) = true
!(10<20) = true
A B A && B A || B !A
False False False False True
False True False True True
True False False True False
True True True True False
37 | P a g e
The following example demonstrates how these operators work.
<!DOCTYPE html>
<html>
<head>
<title>Logical Operators</title>
<script>
//Declaration and initialization of variables
var A = 50, B = 75, lb = "<br>";
document.write("A = " + A + lb + "B = " + B);
document.write(lb + lb);
// Logical AND
document.write("( (A < B) && (B >= A) ) => ");
answer = ((A<B) && (B>=A));
document.write(answer);
document.write(lb + lb);
//Logical OR
document.write("( (A==B) || (B<=A)) => ");
answer = ( (A==B) || (B<=A) );
document.write(answer);
document.write(lb + lb);
//Logical NOT
document.write("!( A != B) => ");
answer = (!( A != B));
document.write(answer);
document.write(lb + lb);
</script>
</head>
<body>
</body>
</html>
38 | P a g e
Operator Name of operators Description Example
It assigns the value of right operand var x = 75
= Assign
into left operand.
It adds both right and left operands, var x =50;
+= Add and assign and assigns the result into the left x += 75;
operand. Then, x = 125
It subtracts the value of right operand var x =75;
-= Subtract and assign from the value of left operand and x -=50;
assigns the result into left operand. Then, x = 25
It multiplies right and left operands, var x = 50;
*= Multiply and assign and assigns the result to the left x * = 75;
operand. Then, x = 3750
It divides the value of left operand by var x = 50;
/= Divide and assign the value of right operand and assigns x /= 5;
the result to left operand. Then, x = 10
It assigns the reminder to left operand var x =50;
%= Modulus and assign after dividing left operand by right x %= 3;
operands. Then, x = 2
39 | P a g e
function display() {
document.write(answer);
document.write(lb + lb);
}
//Assign
restore();
document.write(" x = y => x = ");
answer = (x = y);
display();
40 | P a g e
Lesson 5 : Array and Object
Arrays and objects are both non-primitive data types. Unlike primitive data types, they
are defined by programmers. They are also mutable means their state can be modified
after they are created.
1. First Method:
The first method is well known and generally used for creating an array. The syntax for
that is mentioned as follows.
<body>
<h2 >Fruits: </h2> <p id="para1"></p>
<br><br>
<h2 >Vegetables: </h2> <p id="para2"></p>
<script>
// Array declaration for the list of fruits
var fruit = [" Mangos", " Grapes"," Apple",
" Apricots", " Orange", " Banana Fresh",
" Avocados", " Guava", "Lichi", " Papaya",
" Sapota", " Water Melons"];
41 | P a g e
//Array declaration for the list of vegetable
var Vegetables = [' Ladyfinger', ' Cauliflower', ' Bitter gourd',
' French Beans', ' Cabbage', ' Ridge gourd',
' Spinach', ' Fenugreek',];
document.getElementById("para1").innerHTML=fruit;
document.getElementById("para2").innerHTML=Vegetables;
</script>
</body>
</html>
2. Second Method:
This method is not as popular as the previous method. The syntax for that is mentioned
as follows.
var array_name = new Array();
<script>
// Initializing while declaring
var denomination = new Array(10, 20, 50, 100, 200, 500, 2000);
document.getElementById("para1").innerHTML= denomination;
document.getElementById("para3").innerHTML= animals;
</script>
</body>
</html>
42 | P a g e
It is not compulsory to initialise an array at the time of declaration, one can initialise an
array after declaration. To understand this study the following example.
<!DOCTYPE html>
<html>
<head>
<title>Initialization of Array</title>
</head>
<body>
<h1>List of flowers: </h1>
<p id="para"></p>
<script>
// Creates an array of 5 undefined elements
var flowers = new Array(5);
document.getElementById("para").innerHTML= flowers;
</script>
</body>
</html>
Output:
In the above example, the number within the square brackets which is placed next to the
array variable is called the index.
43 | P a g e
<!DOCTYPE html>
<html>
<head>
<title> Initializing arrays with different data types</title>
</head>
<body>
<h1>Members: </h1>
<p id="para"></p>
<script>
// Creates an array which stores number, string and boolean
var member = [" John", 28," Michael", 16," Steve", 19,
" Adam", 22," Rose", 17, true];
document.getElementById("para").innerHTML= member;
</script>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<title>Index Number</title>
</head>
<body>
<h4>The initial list of elements in the Array.</h4>
<p id="para1"></p><br><br>
44 | P a g e
<p id="para2"></p>
<script>
var grains = ['wheat', ' rye', ' triticale', ' oats',
' oat bran', ' brown rice', ' flaxseed'];
document.getElementById("para1").innerHTML=grains;
Output:
<!DOCTYPE html>
<html>
<head>
<title>Index Number</title>
</head>
<body>
<h4>The initial list of elements in the Array.</h4>
<p id="para1"></p><br><br>
45 | P a g e
<h4>Delete the first item of above mentioned list.</h4>
<button type="button" onclick="toRemove()">Delete the first item!</button>
<script>
var grains = ['wheat', ' rye', ' triticale', ' oats',
' oat bran', ' brown rice', ' flaxseed'];
document.getElementById("para1").innerHTML="Initially: "+grains;
function toRemove(){
//Delete the first element
delete grains[0];
document.getElementById("para1").innerHTML="Updated Array:"+ grains;
}
</script>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<title>Method pop() in JavaScript</title>
</head>
46 | P a g e
<body>
<h3>All the elements of the Array.</h3>
<p id="para1"></p><br>
<h3>The array, after the pop() method executed once. </h3>
<p id="para2"></p><br>
<h3>The array, after the pop() method executed again.</h3>
<p id="para3"></p>
<script>
var animals = [" elephant", " rhinoceros", " tiger",
" lion", " leopard", " snow leopard",
" blackbuck", " bear"];
document.getElementById("para1").innerHTML=animals;
animals.pop();
document.getElementById("para2").innerHTML=animals;
animals.pop();
document.getElementById("para3").innerHTML=animals;
</script>
</body>
</html>
Output:
47 | P a g e
<!DOCTYPE html>
<html>
<head>
<title>Method push() in JavaScript</title>
</head>
<body>
<h3>Initially the array contains the following number of elements.</h3>
<p id="para1"></p><br>
<h3>After pushing one more element. </h3>
<p id="para2"></p><br>
<h3>After pushing one more element. </h3>
<p id="para3"></p>
<script>
var stones = ["Limestone", "Sandstone", "Soapstone",
"Fossil stone", "Travertine", "Marble",
"Slate",];
document.getElementById("para1").innerHTML=stones;
stones.push("Serpentine");
document.getElementById("para2").innerHTML=stones;
stones.push("Granite");
document.getElementById("para3").innerHTML=stones;
</script>
</body>
</html>
Output:
48 | P a g e
<!DOCTYPE html>
<html>
<head>
<title>Method toString() </title>
</head>
<body>
<h3>The array of seasons are mentioned below.</h3>
<p id="para1"></p>
<script>
var seasons = ["winter", " spring", " summer", " autumn",];
document.getElementById("para1").innerHTML= seasons.toString();
</script>
</body>
</html>
Output:
49 | P a g e
Output:
Using the unshift() method an element can be added at the beginning of the array.
<!DOCTYPE html>
<html>
<head>
<title>Unshift() Method</title>
</head>
<body>
<h3>List of fruits is given below.</h3>
<p id="para"></p> <br><br>
<label>Enter the Name of a Fruit: </label>
<input type="text" id="ip">
<button onclick="doStuff()">Add</button>
<script>
var fruits = [" Apple", " Banana", " Mango", " Orange", " Sapota"];
document.getElementById("para").innerHTML = fruits;
function doStuff() {
//Store the value in a variable from the input field.
x = document.getElementById("ip").value;
//Remove the text from the input field.
document.getElementById("ip").value = "";
//Add the value in the array using the variable.
fruits.unshift(x);
//Display the array on the web page.
document.getElementById("para").innerHTML = fruits;
}
</script>
</body>
</html>
50 | P a g e
Output:
document.getElementById("para1").innerHTML
= "<b>Wild Animals:</b>"+wildAnimals;
document.getElementById("para2").innerHTML
= "<b>Domestic Animals:</b>"+domesticAnimals;
document.getElementById("para3").innerHTML
= "<b>Animals:</b>"+animals;
</script>
</body>
</html>
51 | P a g e
Output:
52 | P a g e
The second way is mentioned below.
Output:
53 | P a g e
In both the above examples the objects possess only properties. However, in the
following example, an object also holds a function.
<!DOCTYPE html>
<html>
<head>
<title>An Object with Methods</title>
</head>
<body>
<h4>The Report Card of a student</h4>
<button onclick="studentInfo.fun()">Click</button>
<script>
var studentInfo =
{
rn: 22,
name: "Neha Sharma",
Sbj: "History",
mrk: 82,
fun: function()
{
document.write("Roll No.: " +this.rn+"<br>"+
"Full Name: "+ this.name+"<br>"+"Subject: "+
this.sbj+"<br>"+"Mark: "+this.mrk);
}
}
</script>
</body>
</html>
Output:
54 | P a g e
Lesson 6 : Conditional Statements
55 | P a g e
6.1 If statement
In this, a set of statements executes only when a specified condition is true. If the
condition is false, then those statements cannot be executed.
See the example below to understand the use of this conditional statement.
<html>
<head>
<title> If Conditional statement.</title>
</head>
<body>
<script>
var age;
age = 21;
if (age>18)
{
document.write("You are eligible to vote in the public election.");
}
</script>
</body>
</html>
Output:
56 | P a g e
another set of statements are executed that are present after the “else” keyword and
enclosed in braces.
else
{
statement 1;
statement 2;
.
.
.
statement n;
}
See the example below to understand the use of this conditional statement.
<html>
<head>
<title> If Conditional statement</title>
</head>
<body>
<h3>To verify whether you are eligible for voting or not.</h3>
<label>Enter Your Age: </label> <input type="number" id="txtinpt">
<button type="button" onclick="fun()"> Click!</button>
<h3 id="hd"></h3>
<script>
function fun()
{
age = document.getElementById("txtinpt").value;
if (age >= 18)
{
document.getElementById("hd").innerHTML="You are eligible to vote.";
}
57 | P a g e
else
{
document.getElementById("hd").innerHTML=
"You are not eligible to vote.";
}
}
</script>
</body>
</html>
Output:
Having entered a random age and button clicked event, the output is as follows.
Having entered another random age and button clicked event, the output is as follows.
if (condition) {
statement1;
statement2;
...
}
58 | P a g e
else if (condition) {
statement1;
statement1;
...
}else {
statement1;
statement2;
...
}
...
See the example below to understand the use of this conditional statement.
<html>
<head>
<title> If else if Conditional statement</title>
</head>
<body>
<label> Enter Any number: </label>
<input type="number" id="txtinpt">
<button type="button" onclick="fun()">
Click!</button>
<h3 id="hd"></h3>
<script>
function fun()
{
number = document.getElementById("txtinpt").value;
document.getElementById("txtinpt").value=" ";
if (number > 0)
{
document.getElementById("hd").innerHTML
="You have entered the positive number";
}
else if (number < 0)
{
document.getElementById("hd").innerHTML
="You have entered the negative number";
}
else
{
document.getElementById("hd").innerHTML
="You have entered zero.";
}
}
</script>
59 | P a g e
</body>
</html>
Output:
See the example below to understand the use of this conditional statement.
<html>
<head>
<title> Nested If statement</title>
60 | P a g e
</head>
<body>
<h3>Find out the greater number.</h3>
<!-- accept the inputs from users -->
<label>Enter 1st Number: </label>
<input type="number" id="num1">
<label>Enter 2nd Number: </label>
<input type="number" id="num2">
<button type="button" onclick="fun()">
Click!</button>
<h3 id="hd1"></h3>
<h3 id="hd2"></h3>
<script>
function fun()
{
no1 = document.getElementById("num1").value;
no2 = document.getElementById("num2").value;
if ( no1 != no2)
{
document.getElementById("hd1").innerHTML
="Both the numbers are not same.";
61 | P a g e
Output:
case conditon2:
//block statements;
break;
case condition2:
//block statements;
break;
default:
//block statement;
}
The keyword break is used to end the execution of statements within a switch
statement. If it gets missed by a programmer then each statement is executed
needlessly within the switch statement.
62 | P a g e
See the example below to understand the use of this conditional statement.
<html>
<head>
<Title>Switch statement</Title>
</head>
<body>
<h2>Performance Tracker Page</h2>
<layer>Enter your Grade of the Last Semester: </layer>
<input type="text" id="txtip">
<button type="button" onclick="fun()"> Click </button>
<h4 id="hd1"></h4>
<script>
function fun()
{
grade = document.getElementById("txtip").value;
switch (grade)
{
case 'A': document.getElementById("hd1").innerHTML="Great job!";
break;
default: document.getElementById("hd1").innerHTML
="Provide Valid Grade!";
}
}
</script>
</body>
</html>
63 | P a g e
Output:
Note: Try the same program without a break statement and find out the difference in
the output.
64 | P a g e
Lesson 7: Loops
In computer programming, loops are programming structures which are used to
execute certain sequences of statements until a specific condition is not met. Loops
enable programmers to reuse a set of statements without writing the same statements
again and again in a program. It reduces the length of a program drastically and makes
it very small and brief. Suppose, a program wants to print the same message 100 times,
but writing the same printing statement 100 times is not a wise idea. The reasons are
very simple, it is cumbersome, time-consuming and the length of the program becomes
unusually long. Instead, if a program uses a loop then the entire program summarises
within a few lines of code without any large changes.
There are various types of loops available in JavaScript to repeat a set of lines of codes
such as for, do…while, while, for…in and for..of. This lesson discusses all the loops in
brief.
Initialisation: This component executes first in the loop. This is only used to
declare and initialise variables. It is invalid to place any other statement here.
Make sure that any declaration and initialisation must be terminated with a
semicolon.
65 | P a g e
Condition: This place is where the condition is evaluated. The body of the loop
(the part of a loop enclosed between curly brackets) is executed only when the
condition is true. When the condition becomes false, then the body of the loop is
not executed because the flow of execution jumps to the next statement which
comes just after the loop.
Increment: After the execution of the body of the loop is completed, the flow of
execution jumps to the increment. Here, the value of the loop controlling
variable, either increments or decrements, depending upon the operator which is
used with it.
After this, the condition of the loop is evaluated again and if it is true then all the
remaining steps are executed in the same order as mentioned above. This
procedure continues until the condition becomes false.
66 | P a g e
A for loop is used when a programmer knows beforehand how many times a set of
instructions are required to be executed over and over again. Let us understand the for
loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title> For loop</title>
</head>
<body>
<p id="para"></p>
<script>
function SorryFunc()
{
var Apologies = "";
var i;
for (i = 1; i < 101; i++)
{
Apologies += i+". "+
"<i>Sorry! I will not do it again.</i>"+"<br>";
}
document.getElementById("para").innerHTML = Apologies;
}
</script>
</body>
</html>
Output:
67 | P a g e
7.2 while Loop
Like the for loop, it is also used to execute a set of statements repeatedly until a certain
condition is met. Generally, it is used in a situation when a programmer does not know
how many times a set of statements in the body of the loop needs to be executed.
while (condition) {
//code block to be executed.
}
The structure of the while loop does not have various components like the for loop. It is
rather more simple and straightforward in which the condition is stated first. If it is true,
then the statement or statements in the body of the loop is/are executed. After that, it
again tests the condition whether it is true or false. If it is true, then it executes the body.
The same cycle will continue until the condition becomes false, then the flow of
execution jumps to the next statement after the loop.
68 | P a g e
Let us understand the while loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title> For loop</title>
</head>
<body>
<p>
Click the following button to write 100 times,
<q>Sorry! I will not do it again.</q>
</p>
<p id="para"></p>
<script>
function SorryFunc() {
var Apologies = "";
var i=0;
while(i<101) {
Apologies += i+". "+"<i> Sorry! I will not do it again.</i>"+"<br>";
i++;
}
document.getElementById("para").innerHTML = Apologies;
}
</script>
</body>
</html>
69 | P a g e
The syntax of a do…while loop in JavaScript is mentioned below.
do {
//block code to be executed
} while (condition);
Let us understand the do…while loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title>do...while Loop</title>
</head>
<body>
<h3>Click to display reverse counting from 1000 to 1</h3>
<button type="button" onclick="revCount()">Click!</button>
<h3 id="hd"> </h3>
<p id="para"></p>
<script>
function revCount()
{
var num = 1000;
70 | P a g e
var i = ""
do {
i += num + "<br>";
num--;
} while ( num > 0)
Output:
If a program wants, the variable mentioned in the loop can be declared outside of the
loop. In each iteration of a for…in loop, one property of an object is assigned to the
variable. This loop continues until all the properties of the object are assigned to the
variable.
71 | P a g e
Let us understand the for…in loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title>For in Loop</title>
</head>
<body>
<p id="para"></p>
<script>
var objStudent = { std:"VII", Roll_no:35, name:"Neha Sharma",
subject:"English", mark:65};
var report = "";
var varProperty;
Let us understand the for…of loop with an example which is mentioned below.
<!DOCTYPE html>
<html>
<head>
<title> For ... of Loop</title>
</head>
<body>
<script>
72 | P a g e
var instruments = ['keyboard','maracas','organ',
'pan flute','piano','recorder',
'saxophone','sitar','tambourine',
'triangle','trombone','trumpet',
'tuba','ukulele','violin','xylophone'];
var myvar;
for(myVar of instruments)
{
document.write(myVar +"<br>");
}
</script>
</body>
</html>
Here, pay attention to the fact that the label is not a keyword and it is just a label to
identify a statement or a block code. For more clarity study the following examples.
Example 1:
<html>
<head>
<title>Break and Label</title>
</head>
<body>
<script>
outerloop: // This is the name of label
for (var x= 0; x < 10; x++)
{
document.write("<br>Outerloop: " + x + "<br>");
innerloop:
for (var y= 0; y< 10; y++)
{
if (y > 4 ) break ; // Exit the innerloop
if (x == 3) break innerloop; // Exit the innerloop
73 | P a g e
if (x == 4) break outerloop; // Exit the outerloop
if (y == 5) break ; // Exit the innerloop
document.write("Innerloop: " + y + " <br>");
}
}
document.write("The outerloop has been breaked.");
</script>
</body>
</html>
If one analyses the output of this script by executing it in a web browser. The following
things can be understood with it.
1. A break statement is used to jump out of the loop. This means, once a break
statement is executed in a loop, the further execution of the loop is ceased.
2. A break statement with a label is used to jump out of any code block.
Example 2:
<html>
<body>
<script>
outerloop: // This is the label name
for (var x = 0; x < 5; x++)
{
document.write("<br> Outerloop: " + x + " <br>");
}
document.write("Innerloop: " + y + " <br>");
}
}
</script>
</body>
</html>
If one analyses the output of this script by executing it in a web browser. The following
can be understood with it.
1. A continue statement is used to skip one loop iteration.
74 | P a g e
Lesson 8 : Clock & Counter
This lesson teaches how to make a clock and a counter on a web page using JavaScript.
Here, the first project is the clock and the second is a counter. Before starting these
projects, a programmer must understand a few prerequisites beforehand. Therefore this
lesson first discusses them.
There are four ways by which it can be instantiated. However, this chapter focuses on
the only one that is given below.
Using the following methods a date object can provide the different duration of time.
Method Description
getDate() It provides the days as a number( from 1 to 31).
getDay() It provides week days as a number
getFullYear() It provides the year.
getMonth() It provides the month (from 0 to 11)
getHourse It provides the hour (from 0 to 23).
getMinutes() It gives the minutes (from 0 to 59)
getSeconds() It provides the seconds (from 0 to 59)
getMilliseconds() It gives the milliseconds (from o to 999)
getTime() It gives the time.
75 | P a g e
<body>
<script>
// Instantiation of a date object
var myVar = new Date();
</script>
</body>
</html>
Output:
In JavaScript, there are two such methods which facilitate this. They are mentioned
below.
setTimeout: It calls a function once after an interval time (in milliseconds).
76 | P a g e
setTimeInterval: It calls a function repeatedly after a fixed interval of time(in
milliseconds).
window.setTimeout(myFunction, milliseconds);
window.setInterval(myFunction, milliseconds);
As can be seen, these functions require two parameters which are given as follows.
myFunction: Any function which is required to be called after a time interval.
milliseconds: It is a time period in milliseconds that indicates the time before the
process of a call takes place.
<!DOCTYPE html>
<html>
<head>
<title>setTimeout & setTimeInterval</title>
<script>
function myfunction()
{
setTimeout(myTimer1, 2000);
setInterval(myTimer2, 2500);
}
function myTimer1()
{
alert("Hello! How are you?");
}
function myTimer2()
{
document.getElementById("para").innerHTML
+= "<p>How may I assist you?</p>";
}
</script>
</head>
<body>
<h1>Click the following button and wait for a few seconds.</h1>
<button type="button" onclick="myfunction()">Click Me!</button>
<P id="para"></P>
</body>
</html>
77 | P a g e
In this program, the call of two functions is scheduled with the help of setTimeout() and
setTimeInterval(). In which, when a user clicks the button on the web page, then the
myTimer1() function is called after 2 seconds and writes some text on the web page.
Simultaneously, after 2.5 seconds from the button click event one more function
myTimer2() is called and it prints some text on the web page. The myTimer2() function is
constantly being called after every 2.5 seconds and each time it writes some text on the
web page.
<!DOCTYPE html>
<html>
<head>
<title>Clock</title>
</head>
<script>
function clock()
{
//Instantiation of date object
var dt = new Date();
hrs = dt.getHours();
mins = dt.getMinutes();
secs = dt.getSeconds();
ap ="AM";
//formatting of time
if (hrs > 11) { ap = "PM"; }
if (hrs > 12) { hrs = hrs - 12; }
if (hrs == 0) { hrs = 12; }
if (mins < 10) { mins = "0" + min; }
if (secs < 10) { s = "0" + secs; }
78 | P a g e
function addzero(num)
{
if (num<10){num = "0" + num}
return num;
}
</script>
<body onload="clock()">
<h1 id="display"></h1>
</body>
</html>
Output:
A counter is used to count the number of times an event or process takes place
somewhere. Commonly, it is used to count the number of people in various places, for
example, retail shops, shopping malls, etc. In places like that, it is very helpful to prevent
overcrowding and congestion.
This project is an attempt to design a counter on a web page, where one can keep a
record of the number of people present inside a hall (with limited seats) at one time.
This project should not only provide a facility to count up but also count down.
The code for such a counter on the web page is given below.
<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
<style>
#counter{
font-family: "Lucida Console", Courier, monospace;
color:#329c9c;
font-size: 150px;
text-align: center;
}
79 | P a g e
button{
/* to make round edges*/
border-radius: 10px;
background-color:#44f5f5;
border-color:#44ffff ;
color: rgb(255, 255, 255);
font-size: xx-large;
}
table{
border: 5px dotted #44f5f5;
background-color: white;
}
body{
background-color: #44f5f5;
}
h2 {
color: white;
font-size: 50px;
}
</style>
<script>
var i =0;
function increment() {
i++;
display();
}
function decrement() {
i--;
display();
}
function display() {
document.getElementById("counter").innerHTML =i;
}
</script>
80 | P a g e
</head>
<body>
<h2 align ="center">COUNTER</h2>
<table border="1" cellspacing ="30px" align ="center">
<tr>
<td colspan="2" ><h1 id="counter">0</h1></td>
</tr>
<tr>
<td>
<button onclick="increment()">
Add Count
</button>
</td>
<td>
<button onclick="decrement()">
Lower Count
</button>
</td>
</tr>
</table>
</body>
</html>
Output:
81 | P a g e
Lesson 9 : Character counter & Calculator
This lesson demonstrates how to make a character (or letter) counter, a BMI calculator
and a calculator on a web page using JavaScript. Here, the first project is the character
counter, second is a BMI calculator and the third is a fully functional calculator. Before
starting these projects, a programmer must understand a few prerequisites beforehand.
Therefore this lesson first discusses them.
A character counter or letter counter is a tool whereby one can count the total number
of characters in a given text. One might wonder, why would somebody be wary about
the character count of a text? How exactly are such counters helpful?
The answers to such questions are very simple and straightforward, there many online
platforms that limit inputs to a certain number of characters. When a user exceeds such
a limit, then either the input is rejected or only part of it is accepted regardless of the
loss in the actual meaning of the input. Such online platforms include famous social
networking services such as Twitter, Facebook, Instagram, Linkedin, Pinterest, YouTube,
etc.
The code for such a character counter on the web page is given below.
<!DOCTYPE html>
<html>
<head>
<title>Character Counter</title>
</head>
<script>
function counter()
{
var text = document.getElementById("txt").value;
var charCount = text.length;
document.getElementById("para").innerHTML = "Total Character: ";
document.getElementById("count").innerHTML = charCount;
}
</script>
<style>
82 | P a g e
button{
/* to make round edges*/
border-radius: 12px;
background-color:#9b4135;
border-color:#8a382d ;
color: rgb(255, 255, 255);
font-size: x-large;
}
#count{
font-family:"Lucida Console";
color:#9b4135;
font-size: 75px;
text-align: center;
}
table{
border: 25px double #9b4135;
background-color: white;
text-align: center;
}
textarea {
/* sets size of the textarea */
height: 75px;
width: 400px;
}
h1 {
color: rgb(255, 255, 255);
line-height: 10px;
}
body{background-color: #9b4135;}
.lbl{color:#9b4135;}
</style>
<body>
<h1 align ="center">CHARACTER COUNTER</h1>
<tr><td>
<button onclick="counter()">
Get the character count
</button>
</td></tr>
<tr><td>
<p id="para" class="lbl"></p>
<h1 id="count"></h1>
</td></tr>
</table>
</body>
</html>
Base on this formula, in this project, a BMI calculator is to be made on a web page.
Where a user provides height in centimetre and weight in kilogram. Upon the click of a
button, the calculated BMI displays on the web page. The code of such a BMI calculator
is provided below.
84 | P a g e
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
<style>
button{
/* to make round edges*/
border-radius: 10px;
background-color:#0a28cf;
border-color:#06104d ;
color: rgb(255, 255, 255);
font-size: x-large;
}
table{
border: 5px dashed #06104d;
background-color: white;
text-align: center;
}
body{background-color: #0a28cf;}
h1 {
color: rgb(255, 255, 255);
line-height: 10px;
}
</style>
<script>
function calculate()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
var heightInMeter = height/100;
85 | P a g e
//round-up BMI figures up to two-digits only
BMI = BMI.toFixed(2)
86 | P a g e
Output:
<!DOCTYPE html>
<html>
<head>
<title>Eval() Function</title>
<script>
87 | P a g e
eval("alert('This argument is executed by eval()')");
var x = 50;
var y = 80;
var myVar1 = eval("x + y") + "<br>";
var myVar2 = eval("22 / 7") + "<br>";
document.write(myVar1);
document.write(myVar2);
</script>
</head>
<body>
</body>
</html>
Output:
input[type="button"]
{
/* to make edges round */
width:100%;
color: rgb(ff, ff, ff);
88 | P a g e
font-size:40px;
background-color:#9fe6f3;
border-radius: 10px;
border-color:#1ae7ee;
}
input[type="text"]
{
text-align: right;
font-size: 40px;
background-color: white;
border-radius: 10px;
border-color: black ;
width:100%
}
</style>
<script>
//function that displays numbers in the textbox
function display(num)
{
document.getElementById("txtbox").value+=num
}
<body>
<div class = "CalcuName" >JavaScript Calculator</div>
<table>
<tr>
<td colspan="3"><input type="text" id="txtbox"/></td>
<td><input type="button" value="C" onclick="txtClear()"/> </td>
</tr>
89 | P a g e
<td><input type="button" value="3" onclick="display('3')"/> </td>
<td><input type="button" value="+" onclick="display('+')"/> </td>
</tr>
<tr>
<td><input type="button" value="4" onclick="display('4')"/> </td>
<td><input type="button" value="5" onclick="display('5')"/> </td>
<td><input type="button" value="6" onclick="display('6')"/> </td>
<td><input type="button" value="-" onclick="display('-')"/> </td>
</tr>
<tr>
<td><input type="button" value="7" onclick="display('7')"/> </td>
<td><input type="button" value="8" onclick="display('8')"/> </td>
<td><input type="button" value="9" onclick="display('9')"/> </td>
<td><input type="button" value="×" onclick="display('*')"/> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="display('.')"/> </td>
<td><input type="button" value="0" onclick="display('0')"/> </td>
<td><input type="button" value="/" onclick="display('/')"/> </td>
<td><input type="button" value="=" onclick="compute()"/> </td>
</tr>
</table>
</body>
</html>
Output:
90 | P a g e