a b o u t th e a u th o r - javascript-tutor.net · visual basic 2012, made easy, visual basic 2010...
TRANSCRIPT
JavaScript Made Easy Edition 2.0
Year Published: 2020 Liability The purpose of this book is to provide basic guides for people interested in JavaScript.
Although every effort and care has been taken to make the information as accurate as
possible, the author shall not be liable for any error, harm or damage arising from using
the instructions given in this book. Copyright ® 2020 Liew Voon Kiong. All rights reserved. No part of this e-book may be reproduced or distributed, in any form or by any means, without permission in writing from the author.
About the Author
Dr. Liew Voon Kiong holds a bachelor degree in Mathematics, a master degree in
Management and a doctoral degree in Business Administration. He has been involved in
JavaScript programming for more than 10 years. He has also created the popular online
JavaScript Tutorial at javascript-tutor.net . Besides that, he is the author of other
programming books, among them are Visual Basic 2019 Made Easy, Visual Basic 2017 Made Easy, Visual Basic 2015 Made Easy, Visual Basic 2013 Made Easy, Visual Basic 2012, Made Easy, Visual Basic 2010 Made Easy , Visual Basic 2008 Made Easy, Visual Basic 6 Made Easy, HTML & CSS Made Easy, Blockchain Made Easy and Excel VBA Made Easy.
3
Table of Contents
Chapter 1 Introduction to JavaScript 7
1.1 What is JavaScript? 7
1.2 Why use JavaScript? 7
1.3 The Building Block of JavaScript 8
1.3.1 Objects 8
1.3.2 Properties 9
1.3.3 Methods 10
1.3.4 Events 11
Chapter 2 Writing the Code 12
2.1 The Structure of JavaScript 12
Example 2.1 12
2.2 Variables 13
2.2.1 Declaring Variables 13
Example 2.2 14
Example 2.3 15
2.3 Operators 15
2.3.1 Arithmetic Operators 15
Example 2.3 16
Example 2.4 17
2.3.2 Assignment Operators 17
2.3.3 Comparison Operators 19
2.3.4 Logical Operators 20
2.3.5 Conditional Operators 22
Example 2.6 23
Example 2.7 23
Chapter 3 Decision Making 24
3.1 The Structure of Decision-Making Procedure 24
Example 3.1 24
Example 3.2: Using if statements together with comparison operators 25
3.2 Using if and else keywords 25
Example 3.3 26
3.3 Using if, else and else if keywords 26
Example 3.4: Conversion of mark to grade 27
3.4 Looping 27
3.4.1 The for Loop 28
Example 3.5 28
3.4.2 The for in Loop 29
Example 3.6: Retrieving the properties of a document 29
Example 3.7: Retrieving the properties of an object 30
Example 3.8: Calculate the sum of numbers in an array 31
4
The output is shown in Figure 3.2 31
3.4.3 The While Loop 32
Example 3.9 32
Chapter 4 Functions 33
4.1 Definition of Function 33
4.2 Creating User-Defined Functions 33
Example 4.1 34
Example 4.2 Future Value Calculator 36
Example 4.3 Enhanced Future Value Calculator 37
Example 4.4: Maximum Number function 38
Example 4.6 A Graphical Dice 41
Chapter 5 Working with the Document Object 44
5.1 Document Properties 44
5.2 Document Methods 45
Example 5.1: Combining document properties and methods 48
Chapter 6 Working with the Math Object 49
6.1 Math Methods 49
Example 6.1 51
6.2 Math Properties 52
Chapter 7 Working with the String Object 54
7.1 The length Property 54
7.2 The String Methods 54
Example 7.1 57
7.3 Converting Strings to Numbers 58
Example 7.2 59
Chapter 8 Working with the Date Object 60
8.1. The Date Object 60
Example 8.1 Displaying Date and Time 61
8.2 Setting Date and Time 62
Example 8.2 63
Chapter 9 Handling Events 64
9.1 Event Handlers for Links 65
Example 9.1 65
Example 9.2 66
Example 9.3: Future Value Function 67
9.2 Event Handlers for text and textarea 68
Example 9.4: Event Handlers for text Object 69
Example 9.5: Event Handlers for textarea Object 70
9.3 Event Handlers for Buttons 72
Example 9.6: Calculation of Future Value 73
Chapter 10 Working with Form and its Elements 74
10.1 The Structure of the Form 74
5
Example 10.1 Using the onsubmit event handler to send email 76
Example 10.2 77
Example 10.3: Email Validation 77
10.2 Creating the Selection List 79
Example 10.4: To Check Index of a Selected Item 80
Example 10.5: Selection List of Web Links 81
10.3 Creating Radio Buttons 83
Example 10.6 83
Example 10.7: Item Selection Using Radio Buttons 84
Example 10.8: Image Selection 85
10.4 Creating Checkboxes 87
Example 10.9: Code for Item Selection 88
Example 10.10: To Check Status of Multiple Checkboxes 89
Chapter 11 Creating Arrays 90
11.1 Introduction 90
11.2 Declaring and Allocating Arrays 90
11.3: Declaring Arrays with Known Initial Values 92
11.4 Performing Arithmetic Operations on Values of an Array 93
11.5 Tabulating the Values of an Array 94
11.6 Sorting an Array 95
Chapter 12 Working with Frames 98
12.1 Creating Frames 99
12.2 The Hierarchy of Frames 102
12.3 Frames Manipulation Using JavaScript 103
Example 12.1 103
Example 12.2: A Graphical Dice 104
Chapter 13 Creating Cookies 107
13.1 Creating Cookies 107
13.1.1 Creating Temporary Cookies 107
Example 13.1: Cookie Creation 108
13.1.2 Creating Dated Cookies 109
13.2 Reading Cookies 110
Example 13.3: Reading Cookie 111
Example 13.4: Creating and Reading Cookie 112
Chapter 14 Creating Graphics 113
14.1 Drawing a Straight Line 113
Example 14.1 114
14.2 Drawing a Triangle 115
14.3 Drawing a Rectangle with a Solid Color 116
14.4 Drawing a Rectangle with Color in Gradient 119
14.4.1 Linear Gradient 119
14.4.1 Radial Gradient 120
14.5 Drawing an Arc/ Circle 122
6
Chapter 15 Creating Multimedia Content 127
15.1 Creating Banner Ads 127
15.1.1 Creating Rotating Banner Ads 127
15.1.2 Creating Rotating Banner Ads with URL Links 129
15.2 Creating a Slideshow 131
15.3 Creating Rollover Effects 134
15.3.1 Creating Rollovers using HTML 134
Example 30.1 134
15.3.2 Creating Rollovers Involving Text and IMages 135
15.3.3 Creating Rollovers using JavaScript 137
Chapter 16 Creating Objects 139
16.1 Using Literal Notation 139
The syntax to create an object using the literal notation is 139
Example 16.1 140
Example 16.2 141
16.2 Creating an Object using Object Constructor Notation 142
Chapter 17 Creating Animation 144
17.1 The setInterval( ) Method 144
Example 17.1 144
Example 17.2 Displaying Current Time 145
17.2 The ClearInterval( ) Method 146
Example 17.3 146
Example 17.4 147
Example 17.5 147
Chapter 18 Interesting Examples 148
18.1 Animated Digital Dice 148
18.2 Animated Graphical Dice 149
The JavaScript 150
18.3 Animated Butterfly 151
18.4 The Countdown Timer 153
18.5 Basic Calculator 154
18.6 Math Drill 156
18.7 Pythagoras Theorem 158
18.8 Quadratic Graph 161
18.9 Music Player 164
18.10 Video Player 166
7
Chapter 1 Introduction to JavaScript
1.1 What is JavaScript?
JavaScript is a scripting language that works with HTML to enhance web pages and
make them more interactive. Simply say, JavaScript is a scripting language for the
web. It makes up of a sequence of statements that give instructions for the computer to
perform certain tasks, for examples, like providing a response to the user, plays a
song, starts a slideshow, and displays advertisements and more.
JavaScript can turn a web page into a lively interactive platform for the World Wide
Web users! By using JavaScript , you can add sound, date, time, change the color of
the web page according to certain day, pre-validate data entered into a form by the
users before it is sent to the server, search through a database, set options based on
users preferences and much more
JavaScript is a simple programming language with lower learning barrier than the
full-featured programming languages like JAVA, C++, C# and more. Despite its slightly
limited capabilities, it is an object-oriented programming language as it deals with
objects, methods, properties and data.
1.2 Why use JavaScript? Since the invention of the World Wide Web and the creation of various web browsers,
HTML has been the core tool in building and designing web pages. HTML or HyperText
Markup Language was the only language that was used to present text and graphics as
well as links to the World Wide Web users in the 90's of the last century. Although it was
a vast improvement from the earlier text-only browsers like Gopher, it was relatively
8
passive and static; it cannot interact much with the user. That is why we need
JavaScript to make browsing the web a more interesting and useful experience for the Internet users.
With the invention of JavaScript and other web development tools, present day web
pages are smartly designed and packed with fancy features like floating menus,
interactive advertisements, animation and more. Web developers simply cannot create
these features using plain HTML. Among the new tools that help web developers to
create those fancy features, JavaScript is one of the most prominent ones.
1.3 The Building Block of JavaScript As JavaScript is an object oriented programming language; therefore the building block of the JavaScript program code is made up of objects as well as methods, properties and events associated with the objects.
1.3.1 Objects The purpose of a JavaScript program is to manipulate the elements of a web page, such as documents, forms, radio buttons, checkboxes, buttons, windows and more. All these elements are objects.
We identify each object in a web page by its name. For example, the default name of a textbox is Textbox1; if we insert another textbox, the default name will be TextBox2. We can change the name of an object so that it is meaningful and easier for us to identify it, like Txt_StudentName instead of just TextBox1.
9
1.3.2 Properties Every object of a web page has a number of properties. The properties of an object
reflect its characteristics or its behaviors. For example, the properties of a textbox are
name, height, width, background color and foreground color, with border or no border,
font type ,font size and more. We can specify the property of an object using the
following syntax:
Object.property
For example, document.bgcolor= "red" creates a web page with a red background. You can try out the following code using different colors.
<Script> document.bgcolor="Red" </Script>
Other properties of the document object include fgColor, linkColor, vlinkColor and more. By the way, fgColor means foreground color, linkColor means hyperlinks color and vlinkColor means visited links color on a web page. We will introduce more properties in later chapters. Please note that some properties might work in some browsers but not others. You can try out the following code : <html> <head> <script language="javascript"> document.bgColor="black" document.linkColor="cyan" document.vlinkColor="yellow" document.fgColor="white" </Script> </head> <body> </body> </html>
10
1.3.3 Methods A method is a task or command that an object can use to execute an action. For
example, to display a phrase on a web page, we can use the write method; the syntax is
document.write ("Phrase"). For example, document.write("Welcome to
JavaScript") will
display the “Welcome to JavaScript “ message. The general syntax to associate an object with a method is:
Object.Method Since JavaScript is an OOP language, objects are arranged in a hierarchical manner, therefore sometimes we need to define the parent objects too. Like this
ParentObject.ObjectName.ChildObjectName.Method
For example, a document is the parent object of a form and the checkbox is a child object of the form. The following code reflects their hierarchical relationship:
Document.Form1.Checbox1.Click
Beside the write method, methods associated with the form object and the controls that
belong to the form object are frequently used. The common controls of a form are text
box, checkbox and radio button. Another example is the submit method associated with
the form, the code is,
Document.Form1.Submit
We will learn more about methods in later chapters.
11
1.3.4 Events An event is an execution of the JavaScript code triggered by an action from the user
via the keyboard or mouse. For example, clicking the submit button on a web page will
trigger an event that validates the input data and transmits the data to the server.
Examples of events are Click, Load, KeyDown, KeyPress, DblClick , Select
and more.
To respond to the aforementioned events, JavaScript uses event handlers. Some of the common event handlers are:
OnBlur, OnClick, OnChange, OnFocus, OnLoad, onSubmit, OnSelect, OnUnload,
OnMouseOver, OnKeyPress, OnKeyDown
We will learn how to write codes for the event handlers in later chapters.
12
Chapter 2 Writing the Code
JavaScript does not require any special program to create it; you can simply use any
standard text editors such as the Notepad, WordPad , Notepad++ and more to write its
code.
2.1 The Structure of JavaScript
The basic structure of the JavaScript that we embed into a HTML document, is
<Script>
JavaScript Statements
</Script>
This <Script></Script> tags tell the web browser that the content in between is part of a
JavaScript. Let ‘s examine the example below:
Example 2.1
<html> <head> <title>A First Program in JavaScript</title> <script> document.write( "<b> Welcome to Our first program </b>" ) </script> </head> </html>
13
2.2 Variables As we have discussed in chapter 1, JavaScript can accept data from the user, validates
data and sends data to the server. To process and manipulate data, JavaScript uses
variables. A variable is something like a mailbox with a label where its content always
changes. When JavaScript creates a variable, it can store data or values input by the
user or from some other sources. These values can vary as the user can input new data
or values. To identify a particular variable, we always give it a name. For example, if we
want to create a variable to store students’ names, we can name it StudentName. We
divide variables into a few types, as follows:
Numeric – store numerical values String- Store only text Boolean- display True or False
2.2.1 Declaring Variables In JavaScript, we need to declare a variable before we can use it. The keyword we use to
declare a variable in JavaScript is Var1. The statement to declare a variable is
Var VariableName
There are a few rules regarding variable names in JavaScript, these rules are: The variable name must begin with a letter or an underscore (_). It cannot begin with a
number or non-alphabetical characters. For example, name$ and _name are valid
variable names but $name, 2score are invalid variable names. Space is not allowed within a variable name. For example, my name is not a valid variable name but my_name is a valid variable name. Variable names are case sensitive. For example, Garden and garden are different variables in JavaScript. 1 Actually, it is not necessary to use the Var keyword but it is a good practice to include it.
14
JavaScript reserves certain words as statements or commands, these words cannot be
used to assign variable names. Examples of such words are if, for, else, goto,
true, while etc. There are no hard and fast rules that you must obey in choosing a
variable name, but it is best that you choose a name that is meaningful, it will make
debugging your program easier. For example, you can use Tel_No for telephone
numbers, which is better than just using a variable x.
2.2.2 Assigning Values to Variables After you have created a variable, you can assign a value to it. The value can be in the form of number (numeric value), text (String) or Boolean (true or false).The syntax to assign a value in JavaScript is
var variable_name= value
Example 2.2
var mark = 20 var sell_price=100 var age = 40 var height = 180 var temp = 30 var First_Name="George" var car_model = " Laser 100" var Company_Name = ' Ultra Mobile LLC ' var paid = true var alive = false var positive = true
We can also initialize the variable with mathematical operators like this,
Var CostPrice = 50
Var SellPrice =80
Var Profit=SellPrice-CostPrice
15
The above statements initialize the value of profit using the initial value of Sellprice minus the initial value of CostPrice.
Example 2.3 <Script>
Var Author_Name=" John Brandon"; Author_ID="A1234"; ISBN="0-7789-0234-6"; Royalty=100000; document.writeln("Author Name:"+Author_Name+"<BR>");
document.writeln(" Author ID:"+Author_ID+"<BR>");
document.writeln("ISBN:"+ISBN+"<BR>");
document.writeln("Royalty Payment: $"+Royalty)
</Script>
*It is not necessary to put semicolons at the end of each statement in JavaScript, but it is good
practice to include them.
2.3 Operators
2.3.1 Arithmetic Operators JavaScript is not just a scripting language; it can also perform arithmetic calculations. It can interact with online users by receiving data from them, process the data and then output the results to them. The arithmetic operators in JavaScript are shown in Table 2.1
Operators Arithmetic Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Returns the remainder) Example: 10%3=1
++ Increment by 1
- - Decrement by 1
Table2.1: Arithmetic Operators
16
Example 2.3 This example demonstrates how mathematical operations are carried out:
<Script>
Var number1,number2,sum, diff, product, quotient;
number1=10;
number2=8;
sum=number1+number2;
diff= number1-number2;
product=number1*number2;
quotient=number1/number2;
document.write(number1+"+"+number2+"="+sum+<br>);
document.write(number1+"-"+number2+"="+diff+<br>);
document.write(number1+"x"+number2+"="+product+<br>);
document.write(number1+"÷"+number2+"="+quotient+<br>);
</Script>
The results are displayed below:
10+8=18
10-8=2
10x8=80
10÷8=1.25
The following example shows the usage of more arithmetic operators:
17
Example 2.4
<script > var a=10; var b=-10; var c=b%3; a++; b--; document.write(a+"<br>") document.write(b+"<br>") document.write(c) </script>
The output results are shown here 11
-11
-1
2.3.2 Assignment Operators
JavaScript uses assignment operators to assign value to a variable. We have seen how it is done in the earlier section, but we shall examine them in detail here.
The simplest operator to assign value to a variable is to use the equal sign (=). Let's examine some examples below:
Name="John", Price=50, Age=21, Password="qwerty1987";
18
We can also assign values using arithmetic operators. For example,
var Price= 100;
var Cost=80;
var Profit=Price-Cost;
In addition, we can combine two arithmetic operators to form an assignment operator. For example,
var total+=commission;
The above expression in long form is total=total +commission. Let us put the above assignment in a JavaScript, as follows:
<script> var total=100 var commission=15 total+=commission alert("Total="+total) </script>
The value of total is 100+15=115
Table 2.2 shows other assignment operators
Operator Example
-= X-=Y is equivalent to X=X-Y
*= X*=Y is equivalent to X=X*Y
/= X/= is equivalent to X=X/Y
%= X%=Y equivalent to X=X%Y (returns the remainder of X/Y)
Table 2.2: Assignment Operators
19
2.3.3 Comparison Operators In the previous section, we have learned the usage of arithmetic operators in
JavaScript, in this section; we shall introduce the comparison operators. Using
comparison operators, we can compare two values in an expression and evaluate
whether the comparison produces a true or false result. Table 2.3 lists the comparison
operators.
Comparison Operator Description
x==y x is equal to y
x!=y x is not equal to y
x>y x is more than y
x<y x is less than y
x>=y x is more than or equal to y
x<=y x is less than or equal to y
Table 2.3: Comparison Operators
Let us examine the following example: A college student has the following information in the college database.
FirstNname: Ryan
LastName: John
StudentID: RJ2011Fall
Age: 21
Attendance: 30
Year: 3
20
The following JavaScript statements produce true or false results.
Statement True/False
FirstName== ‘Ryan’ True
LastName==”George” False
StudentID==”RJ2012Spring” False
Attendance>20 True
FirstName!= “John” True
Age<20 False
Year>=3 True
Age<=20 False Table 2.4
2.3.4 Logical Operators Besides the comparison operators, JavaScript uses logical operators to make decisions. They are often used to verify information, particularly the userID and password. There are three logical operators here, as shown below:
&& represents AND
|| represents OR
! represents NOT
The logical operators && and II are used together with the comparison operators while the logical operator ! operates by itself. The logical expressions are as follows:
Value1 && Value 2
Value1 || Value 2
! Value
21
For the AND (&&) operator, the logical expression is true if and only if the values on both sides are true, it is false if one of the values is false. The concept is illustrated in the following example:
if (UserName=="John201" && Password=="qwert19" ){ message="Login Successful"}
If both the UserName and the Password are correct, then login is successful. Here is another example:
if ( mark>=60 && mark<80){grade="B"} if the mark is more than and equal to 60 and the mark is less than 80, the grade is B. the OR (||) operator, the logical expression is true if one of the values is true, it is false if only the two values are false. The concept is illustrated in the following example:
if (age>=12 || height>140){Entrance Fee="$10"} If the age of the person is more than 12, even though his or her height is less than 140, the entrance fee is $10. On the other hand, if the person’s age is less than 12 but his or her height is greater than 140; the entrance fee is also $10.
For the Not(!) operator, it reverses the logical statement. The concept is illustrated in the following example:
!(Status= ‘pass’) produces a false result, that is fail. Here is another example:
If (! (stockIndex<1000)) document.write ("The market is good")
The application of the logical operators is shown in Example 2.5 :
22
Example 2.5
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<script>
var age, height, entrancefee;
age=window.prompt("Enter your age:","0");
height=window.prompt("Enter your height:","0");
if (age>=12 || height>=140){entrancefee="$10"} else
{entrancefee="$8"};
document.write("The entrance fee is: "+entrancefee);
</script>
</body>
</html>
2.3.5 Conditional Operators Conditional operators let a JavaScript program execute certain jobs according to certain conditions. The syntax of the conditional operator is
Conditional Expression ? Execution 1: Execution 2
The conditional operator comprises three parts, the first part is the conditional
expression, the second part is execution 1 and the last part is execution 2. The question
mark ? separates the conditional expression and execution 1 whilst the colon : separates
execution 1 and execution 2. If the conditional expression is true, then JavaScript will run
execution 1 and ignore execution2. However, if the conditional expression is false, then
JavaScript will ignore execution 1 and run execution 2. Therefore, the symbol ? and : completely replace If and Else.
23
Example 2.6
In this example, since the expression x>y is false; JavaScript executes the second action, i.e. to display 20 in the browser.
<html> <head> <title>Conditional Operators</title> </head> <body> <script> var x=10; var y=20; x>y?document.write(x):document.write(y); </script> </body> </html>
Example 2.7 We can modify the above example to make it more interactive by prompting the user to enter the values.
<html>
<body>
<script >
var x=window.prompt("Enter first value",0);
var y=window.prompt("Enter second value",0);
x>y?
document.write(x):document.write(y);
</script>
</body>
</html>
24
Chapter 3 Decision Making In the previous chapter, we have learned how to use some decision-making procedures
in JavaScript. In this chapter, we will examine the decision-making procedures in detail.
A decision-making procedure comprises the if keyword, a condition expression and
condition statements.
3.1 The Structure of Decision-Making Procedure The structure of decision-making is:
if (condition expression){ Condition Statements }
If the expression is true, JavaScript will execute the condition statements, otherwise, it will not take any action.
In Example 3.1, if the mark entered is more than 80, then the browser will display Grade=80, otherwise it will not show anything.
Example 3.1
<html>
<body>
<script>
var mark=window.prompt("Enter your mark:","0");
if(mark>=80) { document.write("Grade="+"A")};
</script>
</body>
</html>
25
Example 3.2: Using if statements together with comparison operators
<script>
var firstNumber, secondNumber;
firstNumber = window.prompt( "Enter first Number:", "0" );
secondNumber = window.prompt( "Enter second integer:", "0" );
document.writeln( "<H1>Comparison Output</H1>" );
document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); // Creates table
if ( firstNumber == secondNumber )
document.writeln( "<TR><TD>" + firstNumber + " = " + secondNumber + "</TD></TR>" );
// Creates rows and columns
if ( firstNumber != secondNumber )
document.writeln( "<TR><TD>" + firstNumber + " Not equal to " + secondNumber +
"</TD></TR>" );
if ( firstNumber < secondNumber )
document.writeln( "<TR><TD>" + firstNumber + " < " + secondNumber + "</TD></TR>" );
if ( firstNumber > secondNumber )
document.writeln( "<TR><TD>" + firstNumber + " > " + secondNumber + "</TD></TR>" );
// Display results document.writeln( "</TABLE>" ); </SCRIPT>
3.2 Using if and else keywords
The syntax of using if and else keywords is
if (Expression){ condition statement 1 } else {condition statement 2}
If the expression is true, JavaScript will execute condition statement 1, otherwise it will execute condition statement 2.
26
In the following example, if height is more than or equal to 180, the browser will show the message "Congratulations! You are selected”. Otherwise, it will show the message "Sorry, you are not selected".
Example 3.3
<script> var mark=window.prompt("Enter your height in cm:","0"); if(mark>=180)document.write("Congratulations! You are selected"); else document.write("Sorry, you are not selected"); </script>
3.3 Using if, else and else if keywords
If there are multiple expressions and conditions, we then need to include the else if keyword.
if (condition expression 1 ){ condition statement 1;}
else if(condition expression 2) { condition statement 2;}
else if(condition expression 3) { condition statement 3;}
else { condition statement 4;}
Let’s examine the application in Example 3.3
27
Example 3.4: Conversion of mark to grade
<html>
<head>
<title>Examination Grade</title>
</head>
<body>
<h2><font face="Arial">The grade will be shown below when you enter
the mark</font></h2>
<script>
var mark;
mark=window.prompt("Enter your mark:","0")
if (mark>=80) {document.writeln("Grade="+"A");}
else if (mark>=60 && mark<80) {document.writeln("Grade="+"B");}
else if (mark>=50 && mark<60) {document.writeln("Grade="+"C");}
else if (mark>=40 && mark<50) {document.writeln("Grade="+"D");}
else if (mark>=30 && mark <40) {document.writeln("Grade="+"E");}
else {document.writeln("F");}
</script>
</body>
</html>
3.4 Looping
Another kind of decision-making procedure in JavaScript is looping. Looping is a
procedure whereby the execution is repetitive and will only terminate until a certain
condition is met. There are two types of loops, the for loop and the while loop.
28
3.4.1 The for Loop
The for loop lets JavaScript execute the statements repeatedly until it meets certain conditions. The syntax is:
for (initial expression; condition expression; loop expression)
{ Statements}
Example 3.5
<html> <head> <title>For Loop</title> </head> <body> <script> var sum=0; for (n=0; n<11; n++) { sum+=n ;} document.write("sum="+sum); </script> </body> </html>
In the above example, the initial expression is n=0, the condition expression is n<11 and the loop expression is n++. It means the loop will stop only when n is more than 11. The statement sum+=n means n is added to sum in every repetition. Finally, the browser will display the final value of sum, which is 55.
29
3.4.2 The for in Loop
The for in loop is a special loop that is used to retrieve the properties of JavaScript objects. The syntax is
for (property in object) {statements}
Example 3.6: Retrieving the properties of a document <html> <head> <title>For...In Loop 1</title> </head> <body> <script> for (property in document){ document.write(property); document.write('<br>');} </script> </body> </html>
The above JavaScript code will display the properties of the document object in the browser window, as shown in Figure 3.1
Figure 3.1
30
Example 3.7: Retrieving the properties of an object <html> <head> <title>For...In Loop</title> </head> <p>Click the button to loop through the properties of the car.</p> <button onclick="myFunction()">Run</button> <p id="car"></p> <script> function myFunction() { var Car = {model:"Toyota Camry", Capacity:"2500cc", Year:2020}; var text=" " ; var x; for (x in Car) { text+=Car[x]; } document.getElementById("car").innerHTML = text; } </script> </html>
* document.getElementById() is a DOM method that returns an element with the value of the id attribute that matches. The innerHTML property is used to retrieve the content.
The output is shown in Figure 3.2
Figure 3.2
31
Example 3.8: Calculate the sum of numbers in an array <html> <head> <title>For...In Loop</title> </head> <p>Click the Calculate button to the numbers.</p> <button onclick="myFunction()">Calculate</button> <p id="num"></p> <script> function myFunction() { var Num = {num1:100, num2:200, num3:300}; var text=" " ; var x; var n=0; for (x in Num) { n+=Num[x];
} document.getElementById("num").innerHTML =n; } </script> </html>
The output is shown in Figure 3.2
Figure 3.3
32
3.4.3 The While Loop
The while loop allows us to control the number of times a procedure is performed. It is important to make sure that the repetition is not endless. The structure of the while loop is as follows:
While (condition) { statements}
JavaScript executes the statements as long as the condition is true. Let us look at this simple example:
While (n<=10) {message+='Keep going'; n++}
After the final loop, the string message should contain ten phrases of ‘keep going’
In Example 3.9, clicking the Calculate button produces a dialog box 8 times
prompting the user to enter the marks, then sum up the marks and display the
average mark.
Example 3.9
<html> <head> <title>The While Loop</title> </head> <button onclick="myFunction()">Calculate</button> <p id="answer"></p> <script> function myFunction(){ var mark1,mark2,avg; var sum=0; var counter=1; while(counter<=8) { mark1=window.prompt("Enter your mark","0"); mark2=parseInt(mark1); sum=sum+mark2; counter=counter+1;} avg=sum/8; document.getElementById("answer").innerHTML =avg; ;} </script> </html>
33
Chapter 4 Functions
4.1 Definition of Function A function is a type of program, or part of a program, that can be called from the main
JavaScript program to perform certain tasks. We can also define a function as a module
of the main JavaScript program. A professionally written JavaScript program usually
consists of numerous functions. It is easier to construct , debug and maintain a large
program that is made up of smaller modules, because the programmer needs only
debug a module or modules if certain errors occur, instead of having to search for the
whole program and trying to locate the error code.
There are two kinds of functions in JavaScript , the built-in functions and the user-defined
functions. Built-in functions are also known as methods that are linked to certain objects.
For example, functions that are linked to the Math object are round, pow and more.
There are also string manipulation functions, date, time functions, and many more.We
shall learn about these functions in later chapters.
4.2 Creating User-Defined Functions To create or define a JavaScript function, you will have to write a set of JavaScript codes.
When we write a function, we often need to declare some variables within the function.
You can declare the variables by listing them within parentheses after the function name.
These variables are also known as parameters. They are also known as the local
variable, which means that they are known only in the function in which they are defined.
The syntax to create a function is:
function NameOfFuntion(parameter1, parameter2, parameter3,..)
{Statements}
34
For example, you can write a simple welcoming message function as follows:
function Message()
{ alert("Welcome to JavaScript Function")
However, you need to create an event to call the function. Here I shall show you how to create a click event. You can use the code as follow:
<form>
<input type="button" onclick="Message()" value="View Message">
</form>
The complete code is shown in Example 4.1
Example 4.1 <html> <head> <title>Function</title> </head> <body> <script> function Message() {alert("Welcome to JavaScript Function"); } </script> <input type="button" onclick="Message()" value="View Message"> </form> </html>
When you click the view message button, the message "Welcome to JavaScript Function" will pop up as shown in Figure 4.1
35
Figure 4.1 Let’s examine another example. This example illustrates a financial calculator that
calculates the future value of a present sum invested for a number of years
compounded on a certain annual interest rate. In this example, we create a function that
can perform the calculation. This function comprises three parameters: present
value, number of years and annual interest rate. Let’s use the function name FV to denote the Future Value and PV to denote the present value, n to denote the number of years and r to denote the annual interest rate in percentage form. The formula to calculate the future value is
FV=PV(1+r/100)n
The function written in JavaScript is as follows
function FV(PV, n, r)
{ FV=PV*Math.pow(1+r/100, n):
The future value calculator JavaScript is shown in Example 4.2 .
36
Example 4.2 Future Value Calculator
<html>
<head>
<title>Future Value Calculator</title>
</head>
<body>
<script>
PV=window.prompt( "Enter the present value:", "0" );
n=window.prompt( "Enter number of years :", "0" );
r=window.prompt( "Enter the annual rate:", "0" );
function FV(PV, n, r)
{ FV=PV*Math.pow(1+r/100, n);
document.getElementById("answer").innerHTML =FV;
}
</script>
<input type="button" onclick="FV(PV, n,r)" value="Calculate">
<p>The future value is $<span id="answer"></span></p>
</body>
</html>
When you load the web page, you will be prompted to enter the present value, number
of years and the annual interest rate. If you entered present value=$100,000, number of years=10, annual interest rate=4%, the result will be as follows :
The future value is $148024.42849183443
In the next example, we will create a better future calculator by enhancing its interface and modifying the previous code. Besides that, we will demonstrate how to create a JavaScript file and call that file from the webpage.
First, create a JavaScript file as follows and safe the file as fv.js in the same directory as the webpage.
37
Example 4.3 Enhanced Future Value Calculator
The JavaScript File:
function FV(PV,i,n){
var x=(1+i/100)
var FV=PV*(Math.pow(x,n))
return FV;
}
function Cal_FV(){
var pvalue=parseFloat(document.getElementById("a").value);
var interest=parseFloat(document.getElementById("b").value);
var num=parseInt(document.getElementById("c").value);
var fvalue=FV(pvalue, interest, num);
var fv=fvalue.toFixed(2);
document.getElementById('ans').textContent="The future value is= "+fv;
}
The HTML file:
<html>
<head>
<title>Future Value Calculator</title>
</head>
<body>
<h1><b>Future Value Calculator</b></h1>
<h4>Please enter the values and click the Calculate button to find the
Future value:</h4>
<div style="border:2px solid blue; background-color:#3399ff;width:320px;
text-align:center">
<p>Present Value = <input type="text" size="5" id="a"></p>
<p>Interest Rate = <input type="text" size="5" id="b"></p>
<p>Number of Years= <input type="text" size="5" id="c"></p>
<p>Future Value = $<b id="ans"></b></p>
<p align="center"><input type="button" value="Calculate"
onclick="Cal_FV()"></p>
<script type="text/javascript" src="fv.js"></script> //calling the fv.js
file
</body>
</html>
38
The output is shown overleaf.
Figure 4.2
Example 4.4: Maximum Number function
In this example, we will prompt the user to enter three numbers using the
window.prompt method that produces three subsequent input boxes when the web
page is loaded. We also use the parseFloat function to convert the string into a
floating point or a numeric value so that it can be computed mathematically. The function max comprises three parameters x, y, z. To find the maximum number, we used the conditional keywords if and else if as well the logical operators &&. For example, the program will check for the values of x, y, z and if x>y and x>z, the maximum number is x. However, if y>x and y>z, then y is the maximum number. Finally, if the first two cases are not true, then z is the maximum number.
39
The Code
<html>
<head>
<title>Maximum Number</title> </head>
<body>
<script>
number1=window.prompt("First Number","");
number2=window.prompt("Second Number","");
number3=window.prompt("Third Number","");
value1=parseFloat(number1);
value2=parseFloat(number2);
value3=parseFloat(number3);
MaximumVal=max(value1, value2,value3);
document.write("The Maximum Number is :"+MaximumVal);
function max(x,y,z)
{if ((x>y)&&(x>z)) return x
else if ((y>x)&&(y>z)) return y; else if ((z>y)&&(z>x)) return z; }
</script>
</body>
</html>
Example 4.5: A Dice Function
Rolling a six-sided dice (or die) is essential to many board games and other games, whether a physical game or a computer game. To create a dice function in JavaScript, we need to use the random( ) function that is tied to the Math object. The Math.random( ) function will generate a random number between 0 and 1, as follows:
<script language="javascript">
document.write (Math.random());
</script>
40
Running the script will generate a random number with 16 decimal places, like 0.4495186499923613 In order to generate a random integer from 1 to 6, you can use the following formula:
Math.floor( 1 + Math.random() * 6 )
Math.random()*6 produces a number between 0 and 6. After adding 1, you get a number between 1 and 7, but less than 7. Using the floor function will produce an integer that is less than or equal to the number generated by Math.random()*6 For example, Math.floor(6.9) will round the number to 6. The complete code for the dice function is as follows:
<html>
<head>
<title>Dice Function</title>
<style>
.intro{width:5%;height:5%;font-size:20px;font-weight:bold; border:1px
solid black; text-align:center}
</style>
</head>
<body>
<script> function rolldice()
{ var num=+Math.floor( 1 + Math.random() * 6 );
document.getElementById("outcome").innerHTML =num;
}
</script>
<p>The outcome : <div class ="intro" id='outcome'></div></p>
<input type="button" value="Roll Dice" onclick="rolldice()">
</body>
</html>
41
In the above example, we created a rolldice function. The task is to generate a random integer between 1 and 6(inclusive of 1 and 6) and then displays the output on the web page, as shown in Figure 4.2. The output
Figure 4.3
Example 4.6 A Graphical Dice
In the previous example, we have created a digital dice, but it does not look very cool. In
order to create a visually more appealing dice, we shall create a graphical dice, which
resembles a real dice. In this example, first we have to draw six dice using any
graphics-processing program as shown below. Name each image as 1.jpg, 2.jpg,
3.jpg, 4.jpg, 5.jpg and 6.jpg respectively. Put all these image files in the same
directory as the web page that is running the rolldice( ) function.
Figure 4.4 The dice images Next, you need to load the images randomly using the Math.random function. Besides that, you also need to display the image using the img src tag. The code to load random images is shown below:
document.write ( "<img src = \"" +Math.floor( 1 + Math.random() * 6 )
+".jpg\" width = \"50\" height = \"50\" />")
42
The function Math.floor(1+Math.random()*6) generates integers from 1 to 6, and Math.floor(1+Math.random()*6)+".jpg\" loads the pictures 1.jpg to 6.jpg randomly. The code
<html>
<head>
<title>Dice Function</title>
</head>
<body>
<script>
function rolldice()
{ document.write ( "<img src = \"" + Math.floor( 1 + Math.random() * 6 ) +
".jpg\" width = \"50\" height = \"50\" />");
document.writeln("<br><hr>Click on the refresh button to reload the page"); }
</script>
<input type="button" value="Roll Dice" onclick="rolldice()"></body>
</html>
Loading the web page and then click on the Roll Dice button will generate random images that show the six faces of the graphical dice.
Figure 4.5: The dice images
43
We can improve the previous code further so that the user does not have to refresh the
page to get a new image. This can be done using the DOM element
document.getElementById( ). The code is shown below:
<html>
<head>
<title>Dice Function</title>
</head>
<body>
<script>
function rolldice()
{ var ranNum = Math.floor( 1 + Math.random() * 6 );
var dice = document.getElementById("die");
dice.src=ranNum+".jpg";
}
</script>
<img id="die" src="1.jpg" width="50" height="50">
<br>
<br>
<input type="button" value="Roll Dice" onclick="rolldice()"></body>
</html>
The output
Figure 4.5: The dice images
44
Chapter 5 Working with the Document Object Document objects in JavaScript is one of the most commonly used objects. The main
purpose of the document object is to write something to the web page, or more
appropriately to display text content in a web page. The document object also holds all
the information contained in a web page, such as its background color, its title, the date
the web page was last modified and more. A Document object has properties and
methods.
5.1 Document Properties
As we have learned in Chapter 1, every object of a web page has a number of properties. The properties of an object reflect its characteristics or its behaviours. The document object comprises many properties, as shown in Table 5.1
Properties Description
bgColor Specifies the background color of the web page
fgColor Specifies the foreground color of the web page
title Displays the title of the web page
location Displays URL of the document
lastModified The date the web page was last modified
linkColor Hyperlink color of a web page in hexadecimal value
vlinkcolor Visited hyperlink color of a web page in hexadecimal value
alinkcolor Activated hyperlink color of a web page
links.length Number of links in a web page Table 5.1: Properties of the Document Object
45
The syntax to specify a document property is
document.property = value *Value can be numeric or string For example, to specify the background color of a web age, we can use the following code:
document.bgColor = 'Blue'
Note the value of the color must be placed inside the quotation marks. In addition, the ‘C’ in bgColor must be a capital letter, if you use bgcolor it will not work. Remember that JavaScript is case sensitive. You can also use hexadecimal color codes. For blue, the color code is #0000FF. Therefore document.bgColor = "#0000FF"
also gives a blue background. You can always look up for other color codes on the Internet. To display the title of the web page, the JavaScript code is document.title="My Title"
To specify the color of the hyperlinks in a web page, the JavaScript code is document.linkColor="Cyan" To specify the latest date a web page was modified, the JavaScript code is document.lastModified
5.2 Document Methods
In addition to the properties, the document object also possesses a number of methods. The methods allow the document object to perform some operations.. The syntax to link a document to its method is Document.method
46
The methods are listed in Table 5.2 below:
Method Description
write("text") Display text in the current window
writeln("text") Display text in the current window and add a line after the end of the text.
Clears( ) Clear the window
Close( ) Closes the window
Table 5.2
The most frequently used method is write. This method allows JavaScript to write text. The syntax is
document.write("text")
JavaScript can also create html documents by including html tags in the write method. For example, you can include <h1> tag in the text, like the following example:
document.write("<h>Welcome to JavaScript</h1>")
The text “Welcome to JavaScript'' will be displayed as a Heading 1 text. If you wish to
include a break line, you can use document.write("<br>"). To insert a horizontal
ruler, you can use document.write("<hr>").The writeln method is similar to the
write method as it also displays text in a web page. However, the writeln method
creates a new line in the <pre> and <textarea> structure while the write method does
not. For example,
document.write ("<pre>This is ")
document.write(" JavaScript</pre>") displays the text as “This is JavaScript” Whereas
document.writeln ("<pre>This is ")
document.writeln(" JavaScript</pre>")
displays the text in two lines, like this
47
"This is
JavaScript "
You can create a table using the write method instead of using raw HTMl codes, as illustrated in the following example:
document.write('<table><th>Name</th><th>ID</th>')
document.write('<tr><td>Adam</td><td>001</td></tr>')
document.write('<tr><td>Ben</td><td>002</td></tr>')
document.write('<tr><td>Christin</td><td>003</td></tr>')
document.write('<tr><td>Elene</td><td>004</td></tr>')
document.write("</table>")
The resulting table is shown below:
Name ID
Adam 001
Ben 002
Christin 003
Elene 004
Table 5.3
48
Example 5.1: Combining document properties and methods
<html>
<head>
<title>Document Object</title> </head>
<body>
<script>
document.bgColor = "cyan"
document.linkColor="Magenta"
document.write("This web page title is : "+document.title)
document.write("<br>This web page background color code is:
"+document.bgColor)
document.write("<br>The URL of the web page is: "+document.location)
document.write("<br>This web page was last modified at :
"+document.lastModified)
document.write("<br>The hyperlink color code of this web page is :
"+document.linkColor)
document.write("<br>The visited hyperlink color code of this web page is :
"+document.vlinkColor)
document.write("<br>The active hyperlink color code of this web page is :
"+document.alinkColor)
document.write("<br>The number of hyperlinks of this web page is :
"+document.links.length)
</script>
</body>
</html>
49
Chapter 6 Working with the Math Object
The Math object can be used to perform web-based mathematical calculations. It can
compute numeric data input by the user and then displays its output on the web page.
Therefore, It is very useful for programmers to design online applications that involve
calculations and games. There are many methods and properties of the math object that
we can use to perform mathematical calculations.
6.1 Math Methods Math methods are also known as functions, they are indeed the built-in functions of
JavaScript. Table 6.1 shows a list of the Math methods. Methods Description
abs(x) Returns absolute value of x
acos(x) Returns arc cosine of x (i.e. cos-1x)
asin(x) Returns arc sine of x (i.e. sin-1x)
atan(x) Returns arc tangent of x (i.e. tan-1x)
cos(x) Returns the value of cosine x
sin(x) Returns the value of sine x
tan(x) Returns the value of tangent x
exp(x) Returns the value of e to the power of x (i.e. ex)
log(x) Returns the natural logarithm of x
max(x,y) Returns the greater value of x and y
min(x,y) Returns the greater value of x and y
round(x) Rounds off a number x to the nearest integer
pow(x,y) Returns x to the power of y (i.e. xy)
sqrt(x) Returns the square root of x
ceil(x) Returns the least integer greater than or equal to x
floor(x) Returns the greatest integer less than or equal to x
Table 6.1: Math Methods
50
The syntax of using the Math method is Math.Method, where Math must begin with the
capital M. Using small m just will not work. For example, if you wish to compute the value
of log 100, you write the code as Math.log(100), the value must always be enclosed
within brackets. In order to display the value on the web page, you can use the
Document object together with the write method, and the syntax is
Document.write(Math.log(100))
For trigonometric calculations, you need to convert the values between radian and
degree. For example, to compute the value of cos(60), you need to convert 60 to radian
first otherwise you will get the wrong answer. The conversion can be done using the
formula (60xPI)/180. The syntax written in JavaScript is
Math.cos((60*Math.PI)/180)
Example 6.1 demonstrates the usage of Math methods in JavaScript.
51
Example 6.1 <html>
<head>
<title>Math Methods</title> </head>
<body>
<script>
document.write (("The absolute value of -5.12 is : ")+Math.abs(-5.12));
document.write (("<br>The value of acos0 is : ")+Math.acos(0)+(" in radian")+(" and
")+(Math.acos(0)/Math.PI)*180+(" in degree"));
document.write (("<br>The value of asin(0.5) is : ")+Math.asin(0.5)+(" in radian")+("
and ")+Math.round((Math.asin(0.5)/Math.PI)*180)+(" in degree"));
document.write (("<br>The value of tan 45 is :
")+Math.round(Math.tan((45*Math.PI)/180)));
document.write (("<br>The value of sin 120 is : ")+Math.sin((120*Math.PI)/180));
document.write (("<br>The value of cos240 is : ")+Math.cos((240*Math.PI)/180));
document.write (("<br>The value of exp(3) is : ")+Math.exp(3));
document.write (("<br>The value of ln(3) is : ")+Math.log(3));
document.write (("<br>The value of greater number among 98 and 99 is :
")+Math.max(98,99));
document.write (("<br>The value of smaller number among 98 and 99 is :
")+Math.min(98,99));
document.write (("<br>The value of square root of 200 is : ")+Math.sqrt(200));
document.write("<br>")
</script>
</body>
</html>
The results are shown below: The absolute value of -5.12 is : 5.12
The value of acos0 is : 1.5707963267948965 in radian and 90 in degree
The value of asin(0.5) is : 0.5235987755982989 in radian and 30 in degree
The value of tan 45 is : 1 The value of sin 120 is : 0.8660254037844387
The value of cos240 is : -0.5000000000000004
The value of exp(3) is : 20.085536923187668 The value of ln(3) is : 1.0986122886681097 The value of greater number among 98 and 99 is : 99
The value of smaller number among 98 and 99 is : 98
The value of square root of 200 is : 14.142135623730951
52
6.2 Math Properties
Other than the aforementioned methods, the Math object also comprises a number of properties that also represent certain constant values, as shown in Table 6.2. Property Description
E Euler's constant ( the value is 2.718)
LN10 Natural logarithm of 10 (the value is 2.302)
LN2 Natural logarithm of 2 ( the value is 0.693)
LOG2E Logarithm to the base 2 of e (log2e )
LOG10E Logarithm to the base 10 of e (log10e )
PI The value of PI which is equal 3.1415
SQRT1_2 The square root of half
SQRT2 The square root of 2
Table 6.2 : Math Properties
To use the Math properties, the standard format is
Math.property
For example, Math.LN2 will give you the value of ln2 or loge2. Bear in mind that you have to use capital letter M for the Math object otherwise it will not compute. In order to display the value on a web page, you need to use the document object together with the write method. For example, you can use document.write(SQRT2) to display the value of square root of 2. Example 6.2 demonstrates the usage of Math properties to compute various mathematical values.
53
Example 6.2
<html>
<head>
<title>Math Properties</title> </head>
<body>
<script>
document.write (("The value of e is : ")+Math.E)
document.write (("<br>The value of e is : ")+Math.round(Math.E))
document.write (("<br>The value of ln10 is : ")+Math.LN10)
document.write (("<br>The value of ln2 is : ")+Math.LN2) document.write
(("<br>The value of Pi is : ")+Math.PI)
document.write (("<br>The value of Square root of 1/2 is :
")+Math.SQRT1_2) document.write (("<br>The value of Square root 2 is :
")+Math.SQRT2) document.write("<br>")
document.write("<br><em>The value of e in line 2 has been rounded
off</em>")
</script>
</body>
</html>
The output is shown below: The value of e is : 2.718281828459045
The value of e is : 3
The value of ln10 is : 2.302585092994046
The value of ln2 is : 0.6931471805599453
The value of Pi is : 3.141592653589793
The value of Square root of 1/2 is : 0.7071067811865476
The value of Square root 2 is : 1.4142135623730951
54
Chapter 7 Working with the String Object
The string object in JavaScript is used to manipulate texts and characters. For example, it
can process names, addresses, cell phone numbers, ID, company names, product codes,
serial numbers and more. In fact, strings are the building block of the JavaScript , because
the statements or instructions comprise strings and characters. A string is made up of
letters, numbers and alphanumeric characters such as #, @, $! &,*, \, +, - and
more. The string object has one property and many methods.
7.1 The length Property
The string has only one property, the length property, which is used to find the length of a string, including space. The format is as follows:
String.length
For example,
myString="I love JavaScript"
document.write(myString.length)
returns a value of 17.
7.2 The String Methods
The string object manipulates string using various methods.The syntax of using the String method is
String.Method
where string can be of any acceptable variable name in JavaScript. The methods are shown in Table 7.1
55
Methods Description
big( ) Add the HTML tags <big></big> to the string that displays bigger text.
bold( ) Add the HTML tags <bold></bold> to the string displaying bold text.
fixed( ) Adding the HTML tags <tt></tt> to the string makes the text appear in typewriter style.
italics( ) Add the HTML tags <i></i> to the string displays text in italics.
indexOf(substring, index) Position index in the string. It returns the starting index of the substring.
small( ) Add the HTML tags <small></small> to the string that displays smaller text.
sub( ) Add the HTML tags <sub></sub> to the string and display the text as subscript text.
sup( ) Add the HTML tags <sup></sup> to the string and display the text as superscript text.
strike( ) Add the HTML tags <strike></strike> to the string and display the text as strike-through text.
fontcolor(color) Add the HTML tags <fontcolor(color)></font> to the string and display the text in predefined color.
fontcolor(size) Add the HTML tags <fontcolor(size)></font> to the string and displays the text in predefined size.
toLowerCase( ) Converts string to all lowercase
toUpperCase Converts string to all uppercase
substring(A, B) Extracts the substring starting from position A to position B.
Substr( ) Returns a Substring
chartAt(index) Returns the character located at position index within the string (index with 0)
concat(text) Add text to the end of the string
toString( ) Returns the greatest integer less than or equal to x Table 7.1; String Methods
56
For example, you can define the following string:
var StudentName="John Peterson"
and manipulate the string with various methods below: StudentName.toLowerCase( ) converts the string to john peterson
StudentName.toUpperrCase( ) converts the string to JOHN PETERSON
StudentName.bold( ) displays the string as John Peterson
StudentName.italics( ) displays the string as John Peterson
StudentName.sup( )displays the string as John Peterson
StudentName.sub( ) displays the string as John Peterson
StudentName.strike( ) displays the string as John Peterson
StudentName.substring( 1,6) display part of the string as ohn p
57
Example 7.1
<html>
<body>
<script>
myString="JavaScript Tutorial"
IString=myString.italics( )
SString=myString.small( )
BString=myString.bold( )
BigString=myString.big( )
FixString=myString.fixed( )
subString=myString.sub( )
supString=myString.sup( )
strikeString=myString.strike( )
colorString=myString.fontcolor("red")
StringSize=myString.fontsize("+3")
LCstring=myString.toLowerCase( )
UCstring=myString.toUpperCase( )
PString=myString.substring(1,5)
CharString=myString.charAt(8) concatString=myString.concat(" for you")
SameString=myString.toString( )
document.write("<br>Text in Italics : "+IString)
document.write("<br>Smaller Text : "+SString)
document.write("<br>Text in Bold : "+BString)
document.write("<br>Text with bigger characters : "+BigString)
document.write("<br>Text with typewriter style : "+FixString)
document.write("<br>Subscript text: "+subString)
document.write("<br>Superscript text: "+supString)
document.write("<br>Strike-thru text: "+strikeString)
document.write("<br>Red color text: "+colorString)
document.write("<br>Fontsize +3: "+StringSize)
document.write("<br>Convert to lowercase: "+LCstring)
document.write("<br>Convert to Uppercase: "+UCstring)
document.write("<br>Extracts SubString: "+PString)
document.write("<br>Character at 9th position is : "+CharString)
document.write("<br>Concatenates String: "+concatString)
document.write("<br>Same String: "+SameString)
</script>
</body>
</html> The output is shown overleaf.
58
Text in Italics : JavaScript Tutorial Smaller Text : JavaScript Tutorial Text in Bold : JavaScript Tutorial Text with bigger characters : JavaScript Tutorial Text with typewriter style : JavaScript Tutorial Subscript text: JavaScript Tutorial
Superscript text: JavaScript Tutorial Strike-thru text: JavaScript Tutorial Red color text: JavaScript Tutorial
Fontsize +3: JavaScript Tutorial Convert to lowercase: javascript tutorial Convert to Uppercase: JAVASCRIPT TUTORIAL Extracts SubString: avaS Character at 9th position is : p Concatenates String: JavaScript Tutorial for you Same String: JavaScript Tutorial
7.3 Converting Strings to Numbers
In this section, we will introduce two special methods in JavaScript that convert strings to numbers. When we declare a number enclosed by two quotations marks, JavaScript will consider it as a string. For example, Number1= '20' and Number2= '30' are considered as strings. Performing arithmetic operations on them will give you wrong results. For example, Number1+Number2 will join up the two numbers and you get 2030. In order to perform arithmetic operations, we need to convert the strings to numbers. The two methods that convert strings to numbers are parseInt and parseFloat. parseInt converts a number in a string to a numeric integer while parseFloat converts a decimal number in a string to a numeric number with decimal point. For example, parseInt(6.2)=6 . Please note that parseInt only truncates the decimal part of the number, not rounding it. Therefore, parseInt(6.7)=6, not 7. Referring back to Number1 and Number2 in the previous paragraph, parseInt(Number1)+parseInt(Number2)=50.
59
Example 7.2
<script>
number1=window.prompt("Enter first number")
number2=window.prompt("Enter second number")
total1=parseInt(number1)+parseInt(number2)
total2=parseFloat(number1)+parseFloat(number2)
document.write(total1+"<br>")
document.write(total2)
</script>
Running the Javascript will prompt the user to enter two numbers. The numbers entered are always considered as strings; therefore, we need to use parseInt and parseFloat to convert them to numbers. In the above example, let say number1=2.6 and number2=3.2, then total1=2+3=5 and total2=2.6+3.2=5.8
60
Chapter 8 Working with the Date Object
8.1. The Date Object
The date object is used to manipulate and display date and time. The Methods for displaying date and time are getDate(), getDay(), getHours(),getMinutes(),
getSeconds(), getYear() and more. Each of these methods returns the current time value associated with the method’s name. Table 8.1 describes some commonly used date methods. Method Description
getYear( ) Returns current year
* This method returns three digit year for year starting from 2000 and two-
digit year for years between 1900 and 1999. For example, 2011 appears
as 111. However, IE shows a four-digit year.
getFullYear( ) Returns current year in four-digit format
getDate ( ) Returns the day of the current month
getDay ( ) Returns the day of the current week
getHours( ) Returns the hour since midnight of the current day
getMinutes( ) Returns the minute of the current time
getSeconds( ) Returns the second of the current time
getMonth( ) Returns the current month
toString( ) Returns the computer’s local time
toLocaleString( ) Returns the local time
toGMT String( ) Returns the time in GMT or UTC (Universal Time)
Table 8.1: Some Commonly Used Date Methods
61
The syntax to use the date method is,
Date_Variable.Method
For example, Date_Variable.getDate() returns the day of the current month and Date_Variable .getMinutes() returns the current minutes. To use the Date object, we need to create an instant of the object using the new keyword, Date_Variable=new Date()
Example 8.1 Displaying Date and Time
<html> <head> <title>Date Object</title> </head> <body> <h1>Date and Time Manipulation</h1>
<script>
currentDate=new Date() document.write("<font color=red>Current Year:</font>"+currentDate.getFullYear());
document.write("<br><font color=red>Current Hours:</font>"+currentDate.getHours());
document.write("<br><font color=red>Current Minutes:</font>"+currentDate.getMinutes());
document.write("<br><font color=red>Current Seconds:</font>"+currentDate.getSeconds());
document.write("<br><font color=red>Your computer time is:
</font>"+currentDate.toString());
document.write("<br><font color=red>Your Local time
is: </font>"+currentDate.toLocaleString()); document.write("<br><font color=red>Your Local time in GMT is: </font>"+currentDate.toGMTString());
</script> </body> </html>
The output is shown overleaf.
62
Current Year:2020 Day of the month:11 Current Hours:10 Current Minutes:12 Current Seconds:27 Your computer time is: Sat Apr 11 2020 10:12:27 GMT+0800 Your Local time is: 4/11/2020, 10:12:27 AM Your Local time in GMT is: Sat, 11 Apr 2020 02:12:27 GMT
8.2 Setting Date and Time
We can set the date and time in JavaScript using setDate, setHours,setMinutes,
setMonth, setTime,setYear and setFullYear methods, as shown in Table 8.2.. Method Description
setYear( ) Sets the year
setFullYear( ) Sets the year in four-digit format
setDate ( ) Sets the day of the month
setHours( ) Sets the hour
setMinutes( ) Sets the minute
setSeconds( ) Sets the second
setMonth( ) Sets the month
toString( ) Returns the computer’s local time
toLocaleString( ) Returns the local time
toGMT String( ) Returns the time in GMT or UTC (Universal Time)
Table 8.2: Setting Date and Time Ways to set the date and time are as follows: Mydate.setSeconds(Second of the hour) Mydate.setMinutes(Minute of the hour) Mydate.setHours(hour of the day) Mydate.setDate(day of the month) Mydate.setMonth(Month of the day) Mydate.setFullYear(Year)
63
You need to declare the date variable using
Mydate = new Date()
Example 8.2 <html> <head> <title>Setting date and Time</title> </head> <body> <h1>Setting Date and Time </h1> <script language=javascript> MyDate=new Date() MyDate.setMinutes(35) MyDate.setSeconds(24) MyDate.setHours(13) MyDate.setDate(24) MyDate.setMonth(3) MyDate.setFullYear(2012) document.write("<br><font color=red>The time is set to:
</font>"+MyDate)
</script> </body> </html> This is how the date and time are shown on the web page: The time is set to: Tue Apr 6 2020 13:35:24 GMT+0800
* IE gives you a slight differently display, as shown : The time is set to: Tue Apr 6 13:35:24 UTC+0800 2020
64
Chapter 9 Handling Events
In this chapter, we shall learn about the concept of events in JavaScript. What is an
event? An event is an action that triggers the execution of a JavaScript code. Events
are usually triggered by the web users. For example, clicking the mouse is an event,
dragging the mouse over a hyperlink is also an event. There are three categories of
events or rather event handlers in JavaScript, namely events associated with links,
events associated with forms and its elements, and events associated with windows.
Table 9.1 lists the event handlers.
Event Handlers Description
onClick Occurs when the user clicks on a link or a form element
onDblClick Occurs when the user double clicks on a link or a form element
onFocus Occurs when the user clicks the mouse button or uses the tab to bring attention to a certain form elements such as a text box
onSelect Occurs when the user selects text by dragging the mouse across certain part of text
onBlur Occurs when the user moves away from a currently in-focus form element.
onChange Occurs when the user changes the input into a form element, such as a text box.
onSubmit Occurs when the user clicks the Submit button of a form.
onLoad Occurs when a window is loaded
onUnload Occurs when a window is unloaded
Table 9.1
65
Event handlers are special attributes of the HTML tags and they are used together with the regular attributes. For example, we can use the onmouseover event handler together with the href attribute of the hyperlink tags <a></a>.
9.1 Event Handlers for Links The event handlers for handling events associated with links are onmouseover, onClick and onDblClick. The syntax to include an event handler in a HTMl link is
<a href="URL" eventHandler="event execution">Link Text</a>
Example 9.1 <html>
<head>
<title>Javascript Tutorial</title>
</head>
<body>
<a href="http://javascript-tutor.net" onmouseover=’alert("Welcome to
JavaScript Tutorial")'>JavaScript</a><br>
<a href="http://javascript-tutor.net" onClick='alert("Welcome to
JavaScript Tutorial")'>Javascript Tutorial</a>
</body>
</html>
The HTML displays a web page with two links. When the user moves the mouse over the first link, a pop-up dialog with “Welcome to JavaScript Tutorial” appears. When the user clicks the second link, the same dialog appears, as shown in Figure 9.1.
Figure 9.1
66
You can replace alert in Example 9.1 with other executions such as document.write(‘Welcome to JavaScript’) or some other JavaScript code. For example, you can let it perform a calculation, like this, onmouseover= ‘count=0;count++;alert(count)’
The pop-up dialog will display 1 each time the user drag the mouse over the link. You can even start a loop, like the following example: onmouseover='sum=0; for (n=0; n<11; n++){ sum+=n}document.write("sum="+sum)'; When the user drags the mouse over the link, the web page displays sum=55.
Now we shall see how event handlers for links can trigger the execution of a function.
Example 9.2 <html> <head> <title>Example 9.2: JavaScript event-onmouseover</title> </head> <body> <script> function mylink() {alert("Taking you to the web page now"); location.href="http://javascript-tutor.net/"; } </script> <a href="mypage" onmouseover="mylink()">Click here to visit my web page</a> </body> </HTML> When the user drags the mouse over the hyperlink, it triggers the mylink() function which popup the ‘Taking you to the web page now’ message
67
Example 9.3: Future Value Function
<html> <head>
<title>Future Value Function</title></head>
<body> <script> PV=window.prompt( "Enter the present value:", "0" );
n=window.prompt( "Enter number of years :", "0" );
r=window.prompt( "Enter the annual rate:", "0" );
function FV(PV, n, r) { FV=PV*Math.pow(1+r/100, n);
document.write("The future value after "+n+" years is $"+FV);
} </script> <a href="http://javascript-tutor.net" onmouseover='FV(PV,
n,r)'>Calculate PV</a><br> </body>
When the user drags the mouse over the link, three successive input boxes will appear (as
shown in Figure 9.2). The user can then enter the value of PV, n and r respectively.
Upon dragging the mouse over the link, the function FV is triggered and the value of future value is calculated.
Figure 9.2
68
9.2 Event Handlers for text and textarea The text and textArea are two commonly used form elements in a web page .The text
object creates a one-line text box where the user can type something into it. On the
other hand, the textarea creates a multi-line textbox for the user to type in some text.
These two objects share the same event handlers. The event handlers associated with
text and textarea are listed in Table 9.2
Event Handlers Description
OnClick Occurs when the user clicks inside the text box
OnFocus Occurs when the text box receives focus (same as clicking inside the text box or using a tab key )
OnBlur Occurs when the user clicks outside the text box( it means the text box is losing focus)
OnChange Occurs when the user type some text inside the text box and then clicks outside it.
OnSelect Occurs when the user selects some text inside the text box and then clicks outside it.
Table 9.2: Event handlers for text and textarea
The syntax to create a text object that includes an event handler is as follows: <input type="text" name="textboxName" size="n" value= "initial Text" eventHandler=(event execution)> You can use any name for the text object; we use textboxName. The event handlers are any of those listed in Table 9.2 and event execution can be simply popping up a message dialog box or calling a function. Besides, you can specify the size of the text box by assigning an integer n to the size attribute.For example, you can create the following text box that pops up a message whenever the user changes the content of the textbox and clicks outside the textbox. <input type="text" name="textbox1" size="50" value="Enter Text" onChange =(alert("You have changed the content"))> The text box appears as in Figure 9.3
Figure 9.3: Text Box
69
Example 9.4: Event Handlers for text Object In this example, each event handler triggers the execution of a certain function. <html>
<head>
<title>Textbox Event Handlers</title>
</head>
<body>
<script language="javascript">
function showMessage1(){
window.alert("Please type something");
textbox1.focus()}
function showMessage2(){
window.alert("Please type something");
textbox2.focus()}
function showMessage3(){
window.alert("You have changed the content")
window.alert("The content is "+textbox3.value)}
function showMessage4(){
window.alert("Please come back ")}
function showMessage5(){
window.alert("You have selected some text")
yourtext = document.selection.createRange().text
window.alert("You text you have selected is: "+yourtext ) }
</script>
<input type="text" name="textbox1" size="50" value="Enter Text"
onClick=(showMessage1())><br>
<input type="text" name="textbox2" size="50" onFocus=(showMessage2()) ><br>
<input type="text" name="textbox3" size="50" onChange=(showMessage3()) ><br>
<input type="text" name="textbox4" size="50" onBlur=(showMessage4()) ><br>
<input type="text" name="textbox5" size="50" onSelect=(showMessage5()) ><br>
</body>
</html>
70
In the above example, the showMessage5() function displays the selected text, using the syntax yourtext = document.selection.createRange().text
The syntax to create a textarea object that includes an event handler is as follows: <textarea name="textarea1" cols="m" rows="n" eventHandler=(event execution)></textarea>
You can use any name for the textarea object; we use textarea1 here. The event handlers are any of those listed in Table 9.2 and event execution can be simply popping up a message dialog box or calling a function. Besides, you can specify the size of the textbox by assigning the number of columns m to the cols attribute and number of rows n to the rows attribute. For example, you create a textarea text box that will alert the user to type something whenever he or she clicks the text box and enters using the tab key.
<textarea name="textarea1" cols="m" rows="n" onFocus=(alert("Please type something"))</textarea>
Example 9.5: Event Handlers for textarea Object In this example, each event handler triggers the execution of a certain function
<html>
<head>
<title>Textarea Event Handlers</title>
</head>
<body>
<script> function showMessage1(){
window.alert("Please type something");
textarea1.focus()
}
71
function showMessage2(){
window.alert("Please type something");
textarea2.focus()
}
function showMessage3(){
window.alert("You have changed the content")
window.alert("The content is "+textarea3.value)
}
function showMessage4(){
window.alert("Please come back ")
}
function showMessage5(){
window.alert("You have selected some text")
yourtext = document.selection.createRange().text
window.alert("You text you have selected is: "+yourtext )
}
</script>
<textarea name="textarea1" cols="50" rows="5"
onClick=(showMessage1())></textarea> <textarea
name="textarea2" cols="50" rows="5"
onFocus=(showMessage2())></textarea> <textarea
name="textarea3" cols="50" rows="5"
onchange=(showMessage3())></textarea> <textarea
name="textarea4" cols="50" rows="5"
onBlur=(showMessage4())></textarea>
<textarea name="textarea5" cols="50" rows="5"
onSelect=(showMessage5())></textarea>
</body>
</html>
In the above example, the showMessage5() function displays the selected text, using the syntax yourtext = document.selection.createRange().text
72
9.3 Event Handlers for Buttons Buttons are commonly used elements in a web page because it allows interactivity with
the users. We are used to clicking buttons on the web page such as OK, Click, Cancel,
Yes, No, Continue, Enter, Login and more. We can create these buttons easily using
HTML and JavaScript. In this chapter, we shall show you how to create basic buttons
without the use of the <form> attribute. We will examine the form elements in more
details in the next chapter.
The syntax to create a button with an event handler is as follows: <Input Type="button" value="MyText" OnClick='Event Execution'>
The value attribute is the text that appears on the button. The button object has only one event handler, i.e. the onClick event handler.
For example, we can create a button that pops up the ‘You click me” message when the user clicks on the buttons. <Input Type="button" VALUE="Click Here" onClick='alert("You click me")'>
The button appears as in Figure 9.4
Figure 9.4
73
Example 9.6: Calculation of Future Value <html>
<head>
<title>Future Value Calculator</title>
</head>
<body>
<script>
PV=window.prompt( "Enter the present value:", "0" )
n=window.prompt( "Enter number of years :", "0" )
r=window.prompt( "Enter the annual rate:", "0" )
function FV(PV, n, r)
{ FV=PV*Math.pow(1+r/100, n)
document.write("The future value after "+n+" years is $"+FV) }
</script>
<Input type="button" value="Calculate" onClick='FV(PV,n,r)'>
</body>
In the above example, when the user enters the values for PV, n, r and then clicks the
‘Calculate’ button, the onClick event handler will call the FV function which
proceeds to calculate the future value. We will learn about buttons and other form
elements in the next chapter.
74
Chapter 10 Working with Form and its Elements
Form and its elements are important objects for the websites. Almost all websites use
forms to collect some kinds of data from the users. Commercial websites use forms
to process orders, process billings and payments, validate credit cards information,
research the market, get customers' feedback and more. Other types of forms are
membership subscription form, online survey form, online test form, etc.
In order to collect data, we need to create forms. In addition, when data is entered into
the form, we need to process the data. Forms can be created using HTML. To process
forms at the client side, we can use JavaScript. However, when data is submitted to the
server, we need to use server side programs known as CGI programs to process the
data. CGI stands for Common Gateway Interface. CGI programs are written using one
of a number of programming languages such as PERL, PHP,ASP and JSP. The role of JavaScript is to handle some data processing jobs at the client-side. By handling data at client-side, it helps to reduce workload for the server-side. For example, JavaScript can validate data before submitting it to the server.
10.1 The Structure of the Form A form comprises elements or controls that can handle input from the user and execute
events using event handlers. We have already used three form elements in the previous
chapter, i.e. text, textarea and button. Other form elements are checkbox, radio button
and option list. A form can contain any number of these elements.
75
A form is created using the <form></form> tags, all the form elements are defined within these tags. The form can contain several attributes; they are name, action, method, target and the onsubmit event handler.
The following is the syntax to include the attributes:
<form name=”myform” method=’get’ action=”URL” target=”window name” onsubmit=“javascript code”></form>
The method attribute determines the way to submit data to the server through the form;
the default method is get while the other method is post. The action attribute defines
how the browser is handling the form when it is submitted to a CGI program in the
server, typically it is the URL of the CGI program such as
http://www.mydomain.com/cgi-bin/login.cgi. The only event handler associated with form tags is the onsubmit event handler. A form element is defined using the following syntax:
<input type=”elementType” name=”elementName” value=”anyValue”
eventHandler=”JavaScipt code”>
For example, the syntax to create a text box is:
<input type="text" name="mytextbox" size="100" value= "textbox" onFocus=”alert(‘Welcome’)>
while the syntax to create a textarea object is
<textarea name="textarea1" cols="m" rows="n" eventHandler=(event execution)></textarea>
We will discuss syntaxes to define radio buttons and checkboxes in the later section.
76
Example 10.1 Using the onsubmit event handler to send email The onsubmit event handler is used to handle the form submitting process. This example demonstrates how to write JavaScript code for the onsubmit event handler to send email to the address specified by the user. Here we are using the mailto method to open the default email program such as Microsoft outlook to send email. The code <html>
<head>
<title> Send Email</title>
</head>
<body>
<script> function sendMail(form){
emailAdd=mailform.emailbox.value;
location="mailto:"+ emailAdd;}
</script>
<form name="mailform" onsubmit="sendMail(this.form)"> email
address:<input name="emailbox" type="text" value="">
<input type="submit" value="Send email">
</form>
</body>
</html>
Running the script produces the following text box and button.
Figure 10.1
You can modify the above code by alerting the user who leaves the email box blank to enter his or her email address into the box. The code is shown in Example 10.2.
77
Example 10.2
<html>
<head>
<title>Send Email </title>
</head>
<body>
<script>
function sendMail(form){
var emailAdd
emailAdd=mailform.emailbox.value if
(mailform.emailbox.value=="")
alert("your have not filled up your email address") else
location="mailto:"+ emailAdd}
</script>
<form name="mailform" onsubmit="sendMail(this.form)"> email
address:<input name="emailbox" type="text" value="">
<input type="submit" value="Send email">
</form>
</body>
</html>
Example 10.3: Email Validation
We can improve on the previous examples by adding an email validation process. This is to check whether the user has entered a valid email address or not before it is submitted to the server. Here we use the indexOf property of the string object. The indexOf property comprises two parameters, searchValue and fromIndex.
The syntax indexof(searchValue, fromIndex) means it searches the string for the first instance of the string searchValue. If fromIndex is included, it starts
78
searching from that position within the string. It returns the value of the index of the first letter where the string is first found. If searcValue is not found, it returns a value of -1. We include the line mailform.emailbox.value.indexOf('@',0)==-1 to validate email addresses as all email addresses consist of the @ character. If @ is not found, it returns a value of -1 and hence an invalid email address. If nothing is entered, it is also considered an invalid email address. The operator || means the logical operator OR. The code <html> <head>
<title>Email
Validation</title> </head>
<body>
<script> function
sendMail(form){
var emailAdd
emailAdd=mailform.emailbox.val
ue if
(mailform.emailbox.value==""||
mailform.emailbox.value.indexOf('@',0)==-1) //to search for the
character @ alert("Please enter a valid email address")
else
location="mailto:"+ emailAdd}
</script>
<form name="mailform" onsubmit="sendMail(this.form)">
email address:<input name="emailbox" type="text"
value=""> <input type="submit" value="Send email">
</form>
</body>
</html>
79
10.2 Creating the Selection List
A selection list comprises a list of items presented to the users in a list box or in a
drop-down box. The user can see all the items at once in a list box but he or she can
only see one item in a drop-down box, he or she need to click on the small arrowhead on
the right of the drop-down box to see other items which are presented in a drop-down list
To create the selection list, we use the <select></select> tags. To create the
items inside the selection list, we use the <option> tags. We do not need to use the
closing </option> tag. You can use small case letters for both the select and the
option tags. The <select> object consists of two attributes, name and size. The size
attribute determines how many items are shown to the user in the drop-down box. If the
value of size is equal to the number of items, the selection list appears as a list box. If
you do not specify the size, the drop-down box only shows one item. The syntax to
create a selection list is, <select Name= “ mylist” Size= “m”> <option>Item 1 <option>Item 2 <option>Item 3 . . <option>Item n </select>
Each item in the selection list is identified by its index. It starts with index 0. We use the selectedIndex property of the <option> object to identify which item is selected. For example, mylist.selectedIndex=0 means item 1 is selected.
80
Example 10.4: To Check Index of a Selected Item In this example, we create a selection list with five items. We wish to check the index of the selected item. To achieve this, we created the CheckItem( ) function. The function not only shows the index of the selected item but also the item itself. It uses the selectedIndex property to read the index values.
The code <html>
<head>
<title>Selection List</title>
</head>
<body>
<script>
var myitem
function CheckItem(){
myIndex=myform.mylist.selectedIndex
myItem=myform.mylist.options[myIndex].text
alert("The index is "+myIndex)
alert("The item is "+myItem)}
</script>
<Form NAME="myform">
<SELECT Name= "mylist" Size="3">
<OPTION>Item 1
<OPTION>Item 2
<OPTION>Item 3
<OPTION>Item 4
<OPTION>Item 5
</SELECT>
<INPUT TYPE="BUTTON" NAME="button" value="Select an Item and Check the
index" onClick="CheckItem()">
</Form>
</body>
</html>
81
When the user select an item and then click the button, the pop-up dialog box will display the index of the selected item, as shown in Figure 10.2 Figure 10.2
Example 10.5: Selection List of Web Links In this example, we created a drop-down box using the <SELECT> and the <OPTION>
elements of the form. We have also created a loadURL function to let the user select the
web link and load the web page in the drop-down box by clicking the button. The code is
follow: <html>
<head>
<title>Selection Drop-Down List</title>
</head>
<body> <p>
<script>
function loadURL( ) {
if (form.list.selectedIndex==0) location="art.html"
if (form.list.selectedIndex==1) location="astro.html"
if (form.list.selectedIndex==2) location="bestsell.html" if
(form.list.selectedIndex==3) location="business.html" if
(form.list.selectedIndex==4) location="children.html" if
(form.list.selectedIndex==5) location="computer.html" if
(form.list.selectedIndex==6) location="health.html"
82
if (form.list.selectedIndex==7) location="mystery.html"
if (form.list.selectedIndex==8) location="horror.html"
if (form.list.selectedIndex==9) location="nonfic.html"
if (form.list.selectedIndex==10) location="romance.html" if
(form.list.selectedIndex==11) location="science.html" if
(form.list.selectedIndex==12) location="scific.html"
if (form.list.selectedIndex==13) location="self.html"
if (form.list.selectedIndex==14) location="sports.html"
if (form.list.selectedIndex==15) location="travel.html"
if (form.list.selectedIndex==16) location="young.html"
if (form.list.selectedIndex==17) location="music.html"
}
</script>
<form name="book" action="" method="get">
<select name="list" size="4">
<option>art and drawing
<option>astronomy <option>best
sellers <option>business &
investment <option>children books
<option selected>computer & internet
<option>health & fitness
<option>mystery
<option>horror & thriller
<option>non fiction
<option>romance
<option>science & nature
<option>science fiction
<option>self improvement
<option>sports & games
<option>travel
<option>young readers' corner
<option>music
</select>
<br><input type="button" name="button" value="select a category and click
here" onclick="loadurl( )">
</form> </body>
</html>
83
Note that we have included the selected attribute to the <option> tag for the Computer and Internet item so that this item is the selected item when the web page is loaded, as shown in Figure 10.3
Figure 10.3
10.3 Creating Radio Buttons The function of the radio buttons is to let the user select one particular item from a group of items. Radio buttons do not allow the user to select more than one item. There should be at least two radio buttons on a form. The code is as follows: <input type="radio" name="Radio_button" value="Item">
Example 10.6 <html> <head>
<title>Radio Buttons</title>
</head>
<body> <form name="myform">
<input type='radio' name='Radio_button' value="Item 1">Item 1<br>
<input type="radio" name="Radio_button" value="Item 2">Item 2<br>
<input type="radio" name="Radio_button" value="Item 3">Item 3
</form>
</body>
</html>
The radio buttons created are shown in Figure 10.4
Figure 10.4: Radio Buttons
84
Note that the values of the radio buttons will not display explicitly unless it is called from the JavaScript code, we shall see in the next example. You still need to type the names out in the HTML code.
Example 10.7: Item Selection Using Radio Buttons In this example , the user is presented with four types of fruits and he or she can choose only one type at one time by clicking the radio button beside the label of a particular fruit. The code is as follow: <html>
<head>
<title>JavaScript Example 19.2</title>
</head>
<body>
<script>
function checkItem()
{for(count=0;count<4;count++) {if
(MyForm.item[count].checked)
alert(MyForm.item[count].value+" is selected")
} }
</script> <form name="MyForm">
<input type="button" value="Select and Click" onclick="checkItem()"><br> <input
type="radio" name="item" value="Apple">
<label>Apple</label><br>
<input type="radio" name="item" value="Orange">
<label>Orange</label><br>
<input type="radio" name="item" value="Grape">
<label>Grape</label><br>
<input type="radio" name="item" value="Melon">
<label>Melon</label><br>
</form>
</body>
</html>
85
Radio buttons are actually an array of radio buttons, defined by using item[count]in
the above example, where count ranges from 0 to 3 in this example. Therefore, item[0] is
the first radio button, item[1] is the second radio button, item[2] is the third radio button
and item[3] is the fourth radio button. The checked property is to show that the particular
radio button is being checked. Using the for loop and the checked property, we can
find out which button is being checked currently. The interface is shown in Figure 10.5
Figure 10.5
Example 10.8: Image Selection
You can modify the above program by asking the user to select an image of his or her choice. Here we have designed six images representing the faces of a dice.
Figure 10.6
We have created six radio buttons to load one of these images when the user clicks on a particular radio button. We named the images as 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg and 6.jpg. To load the images, we use the syntax
document.write ( "<img src = \"" +(Math.round(count)+1)+".jpg\" width =
\"50\"height = \"50\" />")
86
The code
<html>
<head>
<title>Image Selection</title>
</head>
<body>
<script>
function checkItem()
{for(count=0;count<6;count++) {
if (MyForm.item[count].checked)
document.write ( "<img src = \"" + (Math.round(count)+1)+".jpg\"
width = \"50\" height = \"50\" />")
}} </script>
<form name="MyForm">
<input type="button" value="Select and Click" onclick="checkItem()"><br>
<input type="radio" name="item" value="One"> <label>One Dot</label><br> <input type="radio" name="item" value="Two">
<label>Two Dots</label><br>
<input type="radio" name="item" value="Three">
<label>Three Dots</label><br>
<input type="radio" name="item" value="Four">
<label>Four Dots</label><br>
<input type="radio" name="item" value="Five">
<label>Five Dots</label><br>
<input type="radio" name="item" value="Six">
<label>Six Dots</label><br>
</form>
</body>
</html>
The radio buttons are shown in Figure 10.7
Figure 10.7
87
10.4 Creating Checkboxes
Checkboxes are differently from radio buttons. While radio buttons only allow the user to select one option at a time, checkboxes allow the users to select multiple options. Below is an example of checkboxes.
Item1
Item2
Item3
Item4
Item5
The status of a checkbox is either check or unchecked. A checkbox can be created using the following format: <input type="checkbox" name="Checkbox1" value="chkbox1">Item1
88
Example 10.9: Code for Item Selection In this example, the user can verify whether a checkbox is checked or not.
<html>
<head>
<html>
<head>
<title>Item1</title>
</head>
<body>
<script>
function checkstatus()
{ if(MyForm.Checkbox1.checked)
document.write(MyForm.Checkbox1.value+” is selected”);
else
document.write(MyForm.Checkbox1.value+” is not selected”)
} </script>
<form>
<input value=”Click” onclick=”checkstatus()”> <input
Value=”Item1″>Item1 </form> </body>
</html>
89
Example 10.10: To Check Status of Multiple Checkboxes You can modify the above program by adding more than one checkboxes to the page. The code written is able to show the user how many checkboxes are being selected. The Code
<html> <head>
<title> Multiple Checkboxes</title>
</head> <body>
<script>
function checkstatus()
{for(count=0;count<4;count++)
{if (MyForm.MyCheckbox[count].checked)
alert(MyForm.MyCheckbox[count].value+” is selected”);
} }
</script> <form>
<input value=”Click” onclick=”checkstatus()”><br> <input
Value=”Item1″>Item1<br> <input Value=”Item2″>Item2<br>
<input Value=”Item3″>Item3<br>
<input Value=”Item4″>Item4<br>
</form>
</body> </html>
90
Chapter 11 Creating Arrays
11.1 Introduction
An array is a regular data structure comprising a group of individual elements that can be referenced to one or more integer index variables. In JavaScript, the array always starts with the zeroth element. For example, an array comprising ten elements are A[0], A[1], A[2], A[3], A[4],A[5], A[6], A[7], A[8] and A[9]. Let illustrate the above example further. The values of each element of an array are shown in the table 11.1.
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
54 60 23 45 67 90 85 34 20 77 Table 11.1 From the above table, the value of A[0]=54, A[1]=60, A[2]=23 and so forth. We can perform arithmetic operations on the array elements. For example, x=A[1]+A[2]+A[3]=137
The above operations add up the values of three array elements and store the sum in the variable x.
11.2 Declaring and Allocating Arrays
In JavaScript, an array can be declared using a number of ways. If the values of the array are unknown or not initialized at the beginning, we use the following statement: var A= new Array(12)
which create an array (or rather array object) that consists of 12 elements. The operator new allocates memory to store 12 elements of the array. The process of
91
creating a new object is known as creating an instance of the object, in this case an Array object. Different arrays may be created using one single declaration, separated by commas, as follows: var x=new Array(20), y=new Array(15), z= new Array(30)
Another way of declaring an array without allocating memory to store the elements, as follows: var A= new Array()
Example 11.1
<html>
<head>
<script> function Start()
{ var A= new Array(10);
for (var i=0; i<A.length;++i)
A[i]=i*10;
for (var i=0; i<A.length;++i)
document.writeln ((“element “+i+” is “+A[i]+”<br>”); }
</script>
</head> <body>
</body>
</html>
The output is shown below: element 0 is 0 element 1 is 10 element 2 is 20 element 3 is 30 element 4 is 40 element 5 is 50 element 6 is 60 element 7 is 70 element 8 is 80 element 9 is 90
92
Note that we create a function Start to initialize the values of elements in the array using the for loop. The results are output using the document.writeln method. The onload method is to initialize the function Start.
11.3: Declaring Arrays with Known Initial Values
In previous section, we have learned that we can declare an array using the new operator. The new operator declares an array dynamically which means that values are assigned when the script is run. However, if the initial values are specified, we can use another way to declare an array. For example, suppose a group of students obtained the following scores in their JavaScript examination, as follows:
Name Score
Alex 50
Brian 60
Carmen 65
Dave 75
Graham 80
Keynes 68
Morgan 70
Olson 85
Table 11.2
We can declare two arrays from the above date, one for the name and the other one for the score. To declare the name array, we can use the following statement: varStudentName=["Alex","Brian","Carmen","Dave","Graham","Keynes","Morgan","Olson"]
93
The values must be enclosed in a pair of square brackets and separated by commas,
the list of values is also known as initializer list. Note that you do not need to use the new
operator. The subscripts of the array are 0,1,2,3,4,5,6,7 which means
StudentName(0)=Alex, StudentName(1)=Brian and so forth. As for the scores, we use the following statement; var Score=[50,60,65,75,80,68,70,85]
The subscripts are also 0,1,2,3,4,5,6,7 which means Score(0)=50, Score(1)=60 and so forth.
11.4 Performing Arithmetic Operations on Values of an Array We can perform arithmetic operations on the values of an array, such as to obtain the sum and the average values. <html>
<head>
<title>Arithmetic Operations in Array</title>
<script>
function Start()
{ var StudentName=["Alex","Brian","Carmen","Dave","Graham","Keynes","Morgan","O
lson"];
var Score=[50,60,65,75,80,68,70,85] var
sum=0 , average=0;
for (i=0; i<Score.length;i++)
sum+=Score[i];
document.writeln(“Total Score is “+sum+”<br>”)
document.writeln(“Average Score is “+sum/i)
}
</script>
</head>
<body>
</body>
</html>
94
11.5 Tabulating the Values of an Array
We can display the values of the array in the above example in a table easily by writing the following script. Note that you can create a table dynamically using the document.write method and by incorporating the entire HTML tags. You can write all the values using the for loop. The full script is shown below: <html>
<head>
<title>Tabulating Values in Area</title>
<script>
function Start() {
var StudentName=["Alex","Brian","Carmen","Dave","Graham","Keynes","Morgan","O
lson"];
var Score=[50,60,65,75,80,68,70,85] document.writeln(“<table
border=\”1\”"+”width=\”50%\”>”);
document.writeln(“<thead><th>Name</th>”+”<th>Score</th></thead><tbody>”); for
(i=0; i<Score.length;i++)
document.writeln(“<tr><td>”+StudentName[i]+”</td><td>”+Score[i]+”</td></t r>”);
document.writeln(“</tbody></table>”);
}
</script> </head>
<body> </body>
</html>
The output is shown in Table 11.3
95
Name Score Alex 50 Brian 60 Carmen 65 Dave 75 Graham 80 Keynes 68 Morgan 70 Olson 85 Table 11.3
11.6 Sorting an Array When we deal with data, especially massive amounts of data, it is a common practice
to sort the data in a kind of order so that they are easier to manage, analyze and look
up. For example, banks will sort customers’ names in alphabetical order so that they
can send the financial statements according to this order at the end of each month. All
computer programming languages provide certain kinds of sorting methods or
functions, JavaScript is no exception. We have learned about arrays in previous chapters. In those chapters, we have learned
how to perform mathematical operations on data in an array and present them in a table.
In this lesson, we will learn how to sort those data and present them in ascending order.
For example, we have a group of students who took a computer-programming test
recently and obtained the marks as shown in the table below. Now, we can sort the mark
in ascending order.
96
Name of Student Mark
Alex 100
Brian 12
Carmen 29
Dave 42
Graham 18
Keynes 33
Morgan 77
Olson 54
Selina 60
Terrence 85
Sorting data in an array in JavaScript required the use of the built-in method sort. The
sort method examines its argument in the form of a function that is usually known as the
comparator function. The comparator function compares two arguments and returns a
positive value if the first argument is greater than the second argument, returns a zero
value if the arguments are equal and returns a negative value if the first argument is less
than the second argument.
Sort is actually the method of an Array object. Therefore, we can initiate the sort method for the Mark using Mark.sort(compareValues) where compareValues is the comparator function. This function is passed to the sort method as an argument. The complete code to sort the Mark array is shown overleaf.
97
<HTML>
<head>
<script> <!–
function SortData() {
var Mark = [ 100, 12, 29, 42, 18, 33, 77, 54, 60, 85 ];
document.writeln( “<h1>Sorting an Array</h1>” );
ShowArray( “Marks in original order: “, Mark );
Mark.sort( compareValues ); // sort the array
ShowArray( “Marks in ascending order: “, Mark );
}
function ShowArray( Title, myArray ) {
document.writeln( “<p>” + Title +
myArray.join( ” ” ) + “</p>” );
}
function compareValues( value1, value2 )
{ return parseInt( value1 ) – parseInt( value2 );
} </script>
</head><body onload = “SortData()”></body>
</html>
The sorted marks will be 12 18 29 33 42 54 60 77 85 100 in ascending order.
98
Chapter 12 Working with Frames
When we surf the World Wide Web, we normally see a single web page in a single
window. However, there are times when we come across a website that displays multiple
web pages in different sections of the browser window. These different sections are
called frames. In HTML, we can divide a browser window into multiple frames; each
frame can load web pages of its own. Figure 12.1 shows a browser window with four
frames.
Figure 12.1
Frames are useful in many ways. For example, we can use one frame as a navigation
panel and another frame to display the contents. The navigation page remains static
therefore; it is easier for the user to browse through the contents. Besides, we can also
99
use frames to create a slideshow, using the web page in one frame as a control panel
and the other frame to load images. Figure 12.2 shows one of these examples. In this
example, the left frame is the table of contents. When the user clicks on any link in the left frame, the relevant content will appear on the right frame.
Figure 12.2
12.1 Creating Frames To create frames in a web page, we use HTML and to manipulate frames we use
JavaScript. In HTML, we use the <frameset> element and the <frame> elemenet to
create a web page with frames. The syntax to divide a browser window into upper frame
and lower frame is
<frameset rows=”80%, 20%”> <frame src=”Webpage1.htm” name=”page1”> <frame src=”Webpage2.htm” name=”page2”> </frameset>
100
The rows attribute assigns 80% of space to the upper frame and 20% to the lower frame. Since the total percentage is 100%, you can replace the 20% with * if you want them to occupy the whole window, like this <frameset rows=”80%, *”>, the browser can
interpret * to be 20%. You have to reference every frame with a unique name for easy
reference later on especially when you are dealing with JavaScript. You have to exclude
the <body></body> tags in the parent window that contains the <frameset> tags,
otherwise the browsers cannot show the frames. Figure 12.3 shows how it looks in a
browser.
Figure 12.3 The syntax to create a browser window with two columns is
<frameset cols=”30%,*”> <frame src=”Webpage1.htm” name=”page1”> <frame src=”Webpage2.htm” name=”page2”> </frameset>
Figure 12.4 shows how it looks.
101
Figure 12.4 The syntax to create a window with rows and columns is
frameset rows="70%,*">
<frameset cols="30%,*"> <frame src="webpage1.htm" name="page1"> <frame src="webpage2.htm" name="page2 " scrolling="no">
</frameset> <frameset cols="20%,*"> <frame src="webpage3.htm" name="page3"> <frame src="webpage4.htm" name="page4" scrolling="no">
</frameset>
Figure 12.5 shows how it looks.
102
Figure 12.5
12.2 The Hierarchy of Frames The main page that contains the <frameset> element is the master document; we call it
the parent window, or the top-level window. Each frame is a child window. A frame can
again contain other frames, or child windows. It can go many levels down, but it is not a
good practice to create too many frames because it makes the document too crowded
and difficult for the user to navigate. In JavaScript, we can reference the relationship among the parent window and the frames as follows: parent.childname1.childname2
Where frame childname2 is the child window of frame childname1.
103
12.3 Frames Manipulation Using JavaScript
Once we set up frames using the <frameset> element, we can manipulate the frames using JavaScript. Let us examine Example 12.1. In this example, we create two frames. One of the frames is used as a control panel and the other frame for displaying contents.
Example 12.1
The parent Page <html>
<head>
<title>Parent Document</title>
</head> <frameset cols="15%,*">
<frame name="leftpage" src="webpage1.htm"> <frame name="rightpage" src="webpage2.htm">
</frameset>
</html> webpage1.htm
<html> <head>
<title>frame1</title>
</head> <body>
<script language="javascript">
function writeContent(){
content=prompt("write something")
parent.rightpage.document.write(content)
} <input type="button" value="Click to write" onclick="writeContent()">
</body> </html>
104
When we load the parent page, we can see a web page comprising two frames. There is
a ‘Click to write’ button on the left frame. We use the name of the frame to reference the
right frame, using the syntax parent.rightpage.document.write. When the user
clicks the button, he can type something into the pop-up input box and whatever he
types will appear on the right column, as shown in Figure 12.6
Figure 12.6
Example 12.2: A Graphical Dice
In this example, we create a graphical dice using two frames. One of the frames contains
the “Roll Dice” button and the other frame displays the image of the dice. When the user
clicks the “Roll Dice” button, the random image of the dice will appear on the other
window. As the user click on the “Roll Dice” button successively, he will see successive
random images of the dice, as shown in Figure 12.7
105
Dice.html <html>
<head>
<title>Parent Document</title> </head>
<frameset cols="15%,*">
<frame name="leftpage" src="rolldice.htm">
<frame name="rightpage" src="diceResult.htm">
</frameset>
rolldice.htm <html> <head>
<title>Roll Dice</title>
</head>
<body>
<script>
function rolldice()
{ parent.rightpage.document.write ( "<img src = \"" +
Math.floor( 1 + Math.random() * 6 ) +
".jpg\" width = \"50\" height = \"50\" />"+"<br><br>")
} </script>
<form><input type="button" value="Roll Dice" onclick="rolldice()"></form>
<hr>
</body>
</html>
The function rolldice() load the images randomly using the random method of the Math object. It displays the images in the right frame using the syntax parent.rightpage.document.write
106
Figure 12.7
107
Chapter 13 Creating Cookies
Cookie is something that stores information in the user’s computer when he or she visits
a website. The information is to enhance the user's experience in visiting the site like
remembering the preferences of the user. It is not to hack or spy on the user’s computer.
Cookies can store two types of data in a user’s computer; one is a temporary cookie that
expires after the session while the other type is a dated cookie that expires after a
certain date. JavaScript is one of the computer languages that can be used to create cookies. When someone visits a website that contains JavaScript code for creating cookies, cookies will be created and stored in his or her computer.
13.1 Creating Cookies
There are two types of cookies, the temporary cookies and the dated cookies. Temporary
cookies expire after a session that is when the user shuts down a browser. On the other
hand, dated cookies will reside in the user’s computer and expire only after a specified
date.
13.1.1 Creating Temporary Cookies
The syntax to create a temporary cookie is
document.cookie=”cookie_value” * ‘cookie_value’ can be text, numeric value, alphanumeric value or combination of text, numeric value and alphanumeric value.
108
You can also create a cookie using the following syntax: document.cookie=”var_name=value” var_name is the name of the cookie and value is the value of the cookie. For example, if want to store the username of the visitor, you can use document.cookie="username='Robert' " The following example shows you how to create a cookie using value from a text box.
Example 13.1: Cookie Creation <html> <head> <title> Cookie
Creation<title> </head> <body> <script>
function CreateCookie() {document.cookie='name='+studentName.value
alert("Cookie Created") } </script> Enter Student Name:<input type="text" name="StudentName"
> <input type="button" value="Enter" name="Enter"
onClick="CreateCookie()"><br><br> </body> </html>
The function CreateCookie()creates a cookie based on the text entered by the user into the text box, as shown in Figure 13.1
Figure 13.1
109
13.1.2 Creating Dated Cookies
To create a date cookie that only expires after a certain date; you need to set the expiration date. The format to create a dated cookie is Expire_Date= new Date(year, month, date)
Document.cookie= "cookieName" + cookievalue+ ";expires="+Expire_Date.toGMTString()
For example, Expire_Date= new Date(2012, 4, 20)
Document.cookie= "Student Name" +student.value+ ";expires="+Expire_Date.toGMTString() The expiration date is 2012 May 20. Please be aware that the month parameter starts with 0 and ends with 11. Therefore, 0 is January, 1 is February, 2 is March, 3 is April and 4 is May and so on. The complete code is shown in Example 13.2. Example 13.2: Creating Cookie with Expiration Date <html> <head> <title>Creating Cookie with Expiration Date</title>
</head> <body> <script> function CreateCookie() {Expire_Date= new
Date(2012, 4, 20) document.cookie='name='+StudentName.value+"
expires="+Expire_Date.toGMTString()
alert("Cookie Created") } </script> Enter Student Name : <input type="text" name="StudentName" > <input type="button" value="Enter" name="Enter" onClick="CreateCookie()"><br>
</body>
</html>
110
You can also set an expiration date based on the current date. For example, you can set
the expiration date to be six month from now. To do this, we use the getMonth() and
setMonth() methods. Example 13.3 illustrates how to create a cookie that expires six
month from the current date. We use getMonth() to get the current month and then use
setMonth to add number months to the current month and assign this date to the
expiration date. <html> <head> <title>Creating Cookie with Expiration
Date</title> </head> <body> <script> function CreateCookie()
{Expire_Date= new Date Expire_Date=setMonth(Expire_Date.getMonth()+6)
document.cookie='name='+StudentName.value+"
expires="+Expire_Date.toGMTString()
alert("Cookie Created") } </script> Enter Student Name : <input type="text" name="StudentName" > <input type="button" value="Enter" name="Enter" onClick="CreateCookie()">
</body>
</html>
13.2 Reading Cookies After creating a cookie, we can write a JavaScript code to read the contents of the cookie. The syntax to read a cookie
Object.value=document.cookie Object is usually a textbox that can be used to display the cookie.
111
You can also display the cookie in the document itself using the document.write method, like this mycookie= document.cookie document.write(mycookie)
Example 13.3: Reading Cookie
<html> <head> <title>Reading
Cookie</title> </head> <body> <script language="javascript"> function
ReadCookie()
{mycookie=unescape(document.cookie
) showcookie.value=mycookie
document.write(mycookie) } </script> The cookie is:<input type="text" name="showcookie" > <input type="button" value="Show Cookie" name="Display"
onClick="ReadCookie()"> </body>
</html>
The keyword unescape is to remove hexadecimal escape sequences such as %.
112
Example 13.4: Creating and Reading Cookie You can create and then read the cookie on the same page.
<html> <head> <title>Create and Read
Cookie</title> </head> <body> <script>
function CreateCookie()
{Expire_Date= new Date(2012, 4,
18)
document.cookie='name='+StudentName.value+"
expires="+Expire_Date.toGMTString() alert("Cookie Created") } function ReadCookie()
{mycookie=document.cooki
e
document.write(mycookie) } </script> Enter Student Name : <input type="text" name="StudentName" > <input type="button" value="Enter" name="Enter" onClick="CreateCookie()"><br>
<input type="button" value="ShowCookie" name="Display"
onClick="ReadCookie()"> </body>
</html>
113
Chapter 14 Creating Graphics
In this chapter, we shall learn how to create graphics on a webpage using JavaScript.
We can draw straight lines, triangles, rectangles and more.
To draw graphics on an HTML document, we need to create a canvas using the
<canvas> element. However, we cannot draw any graphics with the Canvas element
alone. In order to draw on the canvas, we need to use JavaScript. Besides that, we
need to use the getContext() method which returns an object that provides methods
and properties for drawing on the canvas. The properties and methods of the
getContext("2d") object can be used to draw text, lines, boxes, circles, and more on
the canvas.
To create the canvas, use the following HTML statement:
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3; background-color:beige;">
It creates a canvas with width=300 px and height=150 px. We specify the border style
and color as well as background color using the style attribute.
14.1 Drawing a Straight Line
To draw a straight line, create the DrawLine function as follows:
function DrawLine() { var c = document.getElementById("myCanvas"); var cx = c.getContext("2d"); cx.beginPath(); cx.moveTo(x, y); cx.lineTo(v, w); cx.stroke(); }
114
The getElementById() method returns the canvas element that has the id attribute with
the name myCanvas . The getContext() method returns an object that provides
methods and properties for drawing on the canvas. beginPath begin the drawing and
MoveTo specify the starting point while lineTo specifies the ending point. The Stroke
method actually draws the line on the canvas.
Example 14.1
<html> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3; background-color:beige;"> </canvas><br><br> <input type="button" Value="Draw Line" Onclick="DrawLine()"> <script> function DrawLine() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(80, 20); ctx.lineTo(120, 100); ctx.stroke(); } </script> </body> </html>
The Output
Figure 14.1
115
You can also specify the width of the line using the lineWidth attribute, as follows:
ctx.lineWidth = n; where n is an integer. For example, if you add ctx.lineWidth = 4; to Example 14.1 , a thicker line will appear when you click the draw button, as shown in Figure 14.2.
Figure 14.2
14.2 Drawing a Triangle
Based on the same principle, we can draw a triangle by joining three straight lines.
<canvas id="myCanvas2" style="border: 1px solid #d3d3d3; background-color: beige;" width="300" height="150"> </canvas>
<input type="button" value="Draw Line" onclick="DrawTri()"/> <script> function DrawTri() { var c = document.getElementById("myCanvas2"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(80, 20); ctx.lineTo(80, 100); ctx.lineTo(130, 100); ctx.lineTo(80, 20); ctx.stroke(); } </script>
116
The output
Figure 14.3
14.3 Drawing a Rectangle with a Solid Color We can draw a rectangle and fill it with a certain color using the fillRect() method. The
default color is black. The fillRect() method contains four parameters, as follows:
fillRect(x,y,w,h) x= The x-coordinate of the upper-left corner of the rectangle y= the y-coordinate of the upper-left corner of the rectangle w=the width of the rectangle,(in pixels) h=The height of the rectangle(in pixels)
The following script draws a rectangle with black color.
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> </canvas><br><br> <input type="button" Value="Draw Rectangle" Onclick="DrawRect()"> <script> function DrawRect() { var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillRect(20,20,150,100); }
</script>
117
The Output
Figure 14.4
To align the rectangle to the center of the canvas, you can use the following equations:
w=canvas.width-2x0 h=canvas.width-2y0
w=width of the rectangle,h=height of the rectangle, (x0,y0)=coordinates of upper left corner.
The JavaScript is as follows:
<script> function DrawRect() { var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); var x = c.width-40; var y = c.height-40; ctx.fillRect(20,20,x,y); } </script>
The output is shown in Figure 14.5
118
Figure 14.5
To fill the rectangle with a different color, use the fillStyle property, as follows:
ctx.fillStyle =color
The following script will fill the rectangle with blue color. <script> function DrawRect1() { var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); var x = c.width-40; var y = c.height-40; ctx.fillStyle ="blue" ctx.fillRect(20,20,x,y); } </script> The output is shown in Figure 14.6
119
Figure 14.5
14.4 Drawing a Rectangle with Color in Gradient
14.4.1 Linear Gradient
We use the createLinearGradient() method to create a linear gradient style to fill an object such as a rectangle. It can also be used for other objects such as circles, lines, and text.
The createLinearGradient() method comprises four parameters:
createLinearGradient(x1,y1,x2,y2) x1=the x-coordinate of the start point of the gradient y1=the y-coordinate of the start point of the gradient x2=the x-coordinate of the end point of the gradient y2=the y-coordinate of the end point of the gradient
Further, we need to use the addColorStop() method to specify different colors, and where to position the colors in the gradient object.The following function draws a rectangle and creates a gradient comprising the blue and cyan color.
function DrawRect() { var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); var x = c.width-40; var y = c.height-40; var my_gradient=ctx.createLinearGradient(0,0,0,170); my_gradient.addColorStop(0,"blue"); my_gradient.addColorStop(1,"cyan"); ctx.fillStyle=my_gradient; ctx.fillRect(20,20,x,y); }
120
The Output
Figure 14.6
14.4.1 Radial Gradient
We can also create radial gradient using the createRadialGradient() method, the syntax is:
context.createRadialGradient(x0,y0,r0,x1,y1,r1)
The createRadialGradient() method comprises six parameters:
x0 The x-coordinate of the starting circle of the gradient
y0 The y-coordinate of the starting circle of the gradient
r0 The radius of the starting circle
x1 The x-coordinate of the ending circle of the gradient
y1 The y-coordinate of the ending circle of the gradient
r1 The radius of the ending circle
The following script draws a rectangle and creates a radial gradient comprising the blue and cyan color.(please see overleaf)
121
<html>
<canvas id="myCanvas3" width="300" height="150" style="border:1px solid
#d3d3d3;">
</canvas>
<input type="button" Value="Draw Rectangle" Onclick="DrawRect3()">
<script>
function DrawRect3()
{
var c=document.getElementById("myCanvas3");
var ctx=c.getContext("2d");
var x = c.width-40;
var y = c.height-40;
var my_gradient=ctx.createRadialGradient(75, 50, 5, 100, 120, 100);
my_gradient.addColorStop(0,"blue");
my_gradient.addColorStop(1,"cyan");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,x,y);
}
</script>
</html>
The Output
Figure 14.7
122
14.5 Drawing an Arc/ Circle
We can draw an arc or a circle using the arc() Method. The Javascript syntax to create the arc is as follows:
context.arc(x,y,r,s,e,c)
x The x-coordinate of the center of the circle
y The y-coordinate of the center of the circle
r The radius of the circle
s The starting angle, in radians (0 is at the 3 o'clock position of the arc's
circle)
e The ending angle, in radians
c Specifies whether the drawing should be counterclockwise or
clockwise. False is default, and indicates clockwise, while true
indicates counter-clockwise.
The following script draws an arc in the clockwise direction:
<html>
<head>
<meta charset=utf-8 />
<title>Draw a circle</title>
</head>
<body>
<canvas id="circle" width="200" height="200" style="border:1px solid
#d3d3d3;"></canvas>
<script>
function draw()
{ var canvas = document.getElementById('circle');
var ctx = canvas.getContext('2d'); var X = canvas.width / 2; var Y = canvas.height / 2;
var R = 70;
ctx.beginPath();
123
ctx.arc(X, Y, R, 0, 1 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#334fff';
ctx.stroke();
}
</script>
<input type="button" value="Draw" onclick="draw()">
</body>
</html>
The output
Figure 14.8
If you wish to draw the arc in the anticlockwise direction, change the parameter from false to true, as follows:
ctx.arc(X, Y, R, 0, 1 * Math.PI, true);
The output will be as follows:
Figure 14.9
124
If you wish to draw a full circle, change the value from 1 to 2 in the following line:
ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
The output
Figure 14.10 To draw a solid circle, you need to add the following syntax context.fillStyle='color'; context.fill(); The following JavaScript draws a solid circle: DOCTYPE html>
<html>
<head>
<title>Draw a solid circle </title>
</head>
<body>
<canvas id="circle" width="200" height="200" style="border:1px solid
#d3d3d3;"></canvas>
<script>
function draw()
{
var canvas = document.getElementById('circle');
var ctx = canvas.getContext('2d');
125
var X = canvas.width / 2;
var Y = canvas.height / 2;
var R = 70;
ctx.beginPath();
ctx.arc(X, Y, R, 0, 2 * Math.PI, true);
ctx.lineWidth = 3;
ctx.strokeStyle = 'green';
ctx.fillStyle='Blue';
ctx.fill();
ctx.stroke();
}
</script>
<input type="button" value="Draw" onclick="draw()">
</body>
</html>
The output is shown in Figure 14.11
Figure 14.11 To fill the circle with linear gradient colors, add the following lines
var my_gradient=ctx.createLinearGradient(0,0,0,170);
my_gradient.addColorStop(0,"blue");
my_gradient.addColorStop(1,"cyan");
ctx.fillStyle=my_gradient;
126
The output
Figure 14.12 To fill the circle with radial gradient colors, add the following lines: var my_gradient=ctx.createRadialGradient(75, 50, 5, 100, 120, 100);
my_gradient.addColorStop(0,"blue");
my_gradient.addColorStop(1,"cyan");
ctx.fillStyle=my_gradient; The output
Figure 14.13
127
Chapter 15 Creating Multimedia Content JavaScript can turn a web page into a lively interactive platform for the world wide web
users. In this chapter, we will explore ways to enhance a webpage with multimedia
content.
15.1 Creating Banner Ads Displaying banners ads is a common practice for showing advertisements on web pages
to the visitors. Banners ads are normally created using standard graphic tools such as
Photoshop, Paintbrush Pro, and other software. Banner ads can be static or animated.
15.1.1 Creating Rotating Banner Ads
Rotating banners ads comprises several banner images that constantly rotate on a
webpage at a fixed time interval. You can create these banner images using standard
graphics tools. Let's create four banner images and name them as banner1.jpg,
banner2.jpg, banner3.jpg and banner4.jpg
The JavaScript starts by declaring an array to store the banner images using the new
Array keywords, as follows:
Each element in the array is assigned with an index, starting from 0. In our example,
banner1.jpg is assigned with index 0, banner2.jpg is assigned with index 1, banner3.jpg
is assigned with index 2 and banner3.jpg is assigned with index 3.
To track the index of the current banner, we can assign the index to a variable. Here we
use the variable banner and initialize it with a value 0 to load the first banner image.
Next, we create a function ShowBanners which will display all the banner images at fixed
intervals. This can be achieved by incrementing the index values using the statement
banner++ and when the index value is equal to the total number of elements in the
128
array(denoted by MyBanners.length), the index value is set back to 0, which is the index
of the first banner.
banner++
if (banner==MyBanners.length) {banner=0}
The process is repeated at a fixed time interval using the setInterval () function. The
setInterval () function comprises two arguments, the first is the function to be
activated, i.e the ShowBanners ( ) function and the second one is the duration
measured in milliseconds, 1000 is equivalent to 1 second. We use 2000 which is equal to
2 seconds.
You can set any time interval you wish. We also create another function to stop running
the banner ads, i.e stopbanner() which uses the clearInterval method to stop the
timer. In addition, we need to create two buttons, one is to start the banner ads and the
other one is to stop the banner ads.
The JavaScript
<script >
MyBanners=new Array('banner1.jpg','banner2.jpg','banner3.jpg','banner4.jpg')
banner=0
function runbanners()
{myVar=setInterval(ShowBanners,2000)}
function ShowBanners()
{ if (document.images)
{ banner++
if (banner==MyBanners.length) {
banner=0}
document.ChangeBanner.src=MyBanners[banner]
}
}
129
function stopbanner()
{clearInterval(myVar);} /*stop the banner*/</span>
</script>
The HTML
<input type="button" onclick="runbanners()" value="Run Banners">
<img src="banner1.jpg" style="width:auto; height:auto; max-width:100%" name="ChangeBanner"/>
The Output
Figure 15.1
15.1.2 Creating Rotating Banner Ads with URL Links
Creating rotating banner images will provide the visitor to your webpage with some basic
information. However, if you want the visitor to get more information by clicking on the
banner images, you need to create rotating banner ads that contain URL links.
The JavaScript is basically the same as the previous one but we need to add another
array that comprises the links, as follows:
MyBannerLinks=new Array('URL1','URL2','URL3/','URL4/')
You need to make sure that the arrangement of the links is in corresponding order with
the banner images in the first array. Next, we create the ShowLinks function to link the
130
current banner image to the relevant URL and then assign the URL to the href attribute of
the anchor tag.
To load the banner images with URL links, we insert an anchor tag within the
<body></body> section before the <img> tag that displays the current banner image. The
anchor tag's attribute href is used to call the ShowLinks( ) function when the visitor clicks
on the banner.
The JavaScript
<script>
MyBanners=new Array('banner1.jpg','banner2.jpg','banner3.jpg','banner4.jpg')
MyBannerLinks=new Array('vbtutor.net/','excelvbatutor.com/'onlinebizguide4you.com/','javascript-tutor.net/')
banner=0
function ShowLinks(){
document.location.href="http://www."+MyBannerLinks[banner]
}function ShowBanners()
{ if (document.images)
{ banner++
if (banner==MyBanners.length) {
banner=0}
document.ChangeBanner.src=MyBanners[banner]
setTimeout("ShowBanners()",5000)
}
}
</script>
The HTML
131
<body onload="ShowBanners()">
<center>
<a href="javascript: ShowLinks()">
<img src="banner1.jpg" width="900" height="120" name="ChangeBanner"/></a>
</center>
</body>
15.2 Creating a Slideshow
To create a slideshow, we shall modify the JavaScript code for the rotating banners. The
JavaScript code for the slideshow is identical to the JavaScript code of the rotating
banners but it gives control to the user to choose the banner ads he or she wants to see
by clicking on the forward and backward buttons.
To create the JavaScript slideshow, first of all, you need to create a few banner images
using some graphics tools, or you can snap some photos with your digital camera or your
smartphone. In our example, we have created four images and we named them as
banner1.jpg, banner2.jpg, banner3.jpg, and banner4.jpg. Save the images in the same
folder as the HTML file slideshow.htm which will be used to show the slides.
In the slideshow JavaScript code, we create an array MySlides to store the banner
images using the following statement:
MySlides=new Array('banner1.jpg','banner2.jpg','banner3.jpg','banner4.jpg')
We use the variable Slide to indicate the index of the above array, where 0 represents
the index of the first slide, 1 represents the index of the second slide and so on. We also
created the function ShowSlides(SlideNumber) with the argument SlideNumber.
To call this function, we created two buttons within the body tag, the Forward button, and
the Back button. Clicking the Forward will pass the value of 1 to the argument
132
SlideNumber and clicking the Back button will pass the value of -1 to the argument
SlideNumber. Using the statement:
Slide=Slide+SlideNumber
We can then load the next banner image or the previous banner image.
The following statement is to go back to the first image and avoid the error of loading the
next image after the final image has been reached.
if (Slide>MySlides.length-1){Slide=0
Similarly, the statement
if (Slide<0) {Slide=MySlides.length-1
is to fast forward to the last image and avoid the error of loading the image with the
negative index
The following Statement is to display the current image by referencing the name of the
<img> tag.
document.DisplaySlide.src=MySlides[Slide]
The Slideshow Script
<script>
MySlides=new Array('banner1.jpg','banner2.jpg','banner3.jpg','banner4.jpg')
Slide=0
function ShowSlides(SlideNumber){
{ Slide=Slide+SlideNumber
if (Slide>MySlides.length-1){
Slide=0
}
if (Slide<0) {
133
Slide=MySlides.length-1
}
document.DisplaySlide.src=MySlides[Slide]
}
}
</script>
The HTML
<div>
<P align="center"><img src="banner1.jpg" name="DisplaySlide" width="900" height="120" /><p>
<input type="button" value="Back" onclick="ShowSlides(-1)">
<input type="button" value="Forward" onclick="ShowSlides(1)">
</div>
The Output
Figure 15.2
134
15.3 Creating Rollover Effects
Rollover means a webpage changes when the user moves his or her mouse over an
object on the page. It is often used in advertising. There are two ways to create a rollover,
using plain HTML or using a mixture of JavaScript and HTML. We will demonstrate the
creation of rollovers using both methods.
15.3.1 Creating Rollovers using HTML
The keyword that is used to create rollover is the <onmousover> event. For example, we
want to create a rollover text that appears in a text area. The text "What is rollover?"
appears when the user places his or her mouse over the text area and the rollover text
changes to "Rollover means a webpage changes when the user moves his or her mouse
over an object on the page" when the user moves his or her mouse away from the text
area. The HTML script is shown in Example 30.1
Example 30.1
<HTML>
<head></head>
<Body>
<textarea rows="2" cols="50" name="rollovertext" onmouseover="this.value='What is rollover?'"
onmouseout="this.value='Rollover means a webpage changes when the user moves his or her mouse over an object on the page'"></textarea>
</body>
</html>
Drag your mouse in and out of the text area and see the changes in text.
Figure 15.3
135
We can also create a rollover effect that can change the color of its text using the style
attribute.
<Textarea rows="2" cols="100" onmouseover="this.style.color='red'" onmouseout="this.style.color='blue'">
Move the mouse over this text to change its color to red. Move the mouse away to
change the text color to blue.
</textarea>
The Output
Figure 15.4
15.3.2 Creating Rollovers Involving Text and IMages
This example illustrates how to create a rollover effect that involves text and images.
When the user places his or her mouse pointer over a book title, the corresponding book
image appears.
<html>
<head>
<title>Rollover Effect</title>
</head>
<body>
<table>
<tbody>
<tr valign="top">
<td width="50">
<a><img src="vb2010book.jpg" name="book"></a>
136
</td>
<td><img height="1" width="10"></td>
<td><a onmouseover="document.book.src='vb2010book.jpg'"><b>Visual Basic 2010 Made Easy</b></a>
<br>
<a onmouseover="document.book.src='vb2008book.jpg'"><b>Visual Basic 2008 Made Easy</b></a>
<br>
<a onmouseover="document.book.src='vb6book.jpg'"><b>Visual Basic 6 Made Easy</b></a>
<br>
</td>
</tr>
</tbody>
</table>
</body>
</html>
The Output
Figure 15.5
137
15.3.3 Creating Rollovers using JavaScript
Though HTML can be used to create rollovers , it can only perform simple actions. If you
wish to create more powerful rollovers, you need to use JavaScript. To create rollovers in
JavaScript, we need to create a JavaScript function.
Example 30.4 is similar to Example 30.3 but we have added some JavaScript code. In
this example, we have created an array MyBooks to store the images of three book
covers. Next, we create a ShowCover(book) to display the book cover images on the
page. Finally, we call the ShowCover function using the onmouseover event.
The JavaScript
<script language="Javascript">
MyBooks=new Array('javascriptcover.jpg','vb2013.jpg','vb2010book.jpg','vb2008book.jpg','vb6book.jpg')
book=0
function ShowCover(book){document.DisplayBook.src=MyBooks[book]
}</script>
The HTML
<a onmouseover="ShowCover(0)"><b>JavaScript Made Easy</b></a><br>
<a onmouseover="ShowCover(1)"><b>Visual Basic 2013 Made Easy</b></a><br>
<a onmouseover="ShowCover(2)"><b>Visual Basic 2010 Made Easy</b></a><br>
<a onmouseover="ShowCover(3)"><b>Visual Basic 2008 Made Easy</b></a><br>
<a onmouseover="ShowCover(4)"><b>Visual Basic 6 Made Easy</b></a><br>
<div style="text-align:center">
<img src="javascriptcover.jpg" style="width: 200px; height:auto" name="DisplayBook"/></div>
138
The output
Figure 15.6
139
Chapter 16 Creating Objects
An object is something that has properties and methods. For example, a car has
properties like color, model, and methods such as start, accelerate and stop.
An object in JavaScript also has properties and methods. A JavaScript object actually
comprises variables and functions. A variable inside an object is called a property and a
function inside an object is called a method.
There are two ways to create a JavaScript object, namely using literal notation and using
object constructor notation
16.1 Using Literal Notation
The syntax to create an object using the literal notation is
var objectName={
property1="=value1,
property2="=value2,
..................
.................
proeprtyn=valuen,
MyMethod: MyFunction(){ }
};
140
Example 16.1
<!DOCTYPE html>
<html>
<body>
<p>The Phone Object.</p>
<h3>Model:<b id="model"></b></h3>
<h3> Brand:<b id="brand"></b></h3>
<h3>Price:<b id="price"></b></h3>
<script>
var phone= {model:"Note8", brand:"Samsung",
color:"white",price:"$2000"};
document.getElementById("model").innerHTML = phone.model;
document.getElementById("brand").innerHTML = phone.brand;
document.getElementById("price").innerHTML = phone.price;
</script>
</body>
</html>
The output
The Phone Object.
Model:Note8 Brand:Samsung
Price:$2000
141
Example 16.2
In this example, we create the object student that comprises properties name, height,
and weight. Its method is bmi that calculates the bmi index of a particular student. Notice
that each property comprises a name:value pair and they must be separated by a
comma.
<script>
var student={
name:'George',
height:1.78,
weight:75,
bmi: function(){
var x=this.weight/Math.pow(this.height,2);
var y=x.toFixed(2);
return y;
}
};
var student_Name=document.getElementById('studentname');
student_Name.textContent=student.name;
var student_bmi=document.getElementById('bmi_index');
student_bmi.textContent=student.bmi();
</script>
The output
Student Name:George BMI : 24.69
142
16.2 Creating an Object using Object Constructor Notation
We can create an object in JavaScript using the New keyword and the Object()
constructor function. Bear in mind the O of the Object function must be a capital letter,
otherwise it will not work.
After creating the Object, you can then add properties and methods to it using the dot
notation. Please ensure that each element that adds a property or method should end
with a semicolon. The following JavaScript creates a car object.
var car=new Object();
car.brand='Toyota';
car.model='Camry';
car.capacity='2000cc';
car.stock=10000;
car.booked=3000;
car.checkBalance=function(){
return this.stock-this.booked;
};
var carbrand=document.getElementById('carbrand');
carbrand.textContent=car.brand;
var carmodel=document.getElementById('carmodel');
carmodel.textContent=car.model;
var carbalance=document.getElementById('balance');
carbalance.textContent=car.checkBalance();
143
The corresponding HTML document
<!DOCTYPE html>
<html>
<body>
<h1>Car brand:<b id="carbrand"></b></h1>
<h1>Car Model:<b id="carmodel"></b></h1>
<h2>Number of Cars Left:<b id="balance"></b></h2>
<script type="text/javascript" src="car.js"></script>
</body>
</html>
The Output
Car brand:Toyota Car Model:Camry
Number of Cars Left:7000
144
Chapter 17 Creating Animation
To create animation using javascript, we need to use a kind of timer so that an object
changes according to a certain time interval. In Javascript, we use the setInterval()
method as a timer.
17.1 The setInterval( ) Method
The setInterval() method calls a function or runs an expression at specified intervals (in
milliseconds). The syntax is as follows:
setInterval(myfunction, time interval)
The setInterval method runs a function created by you at a certain time interval in
milliseconds. For example, a time interval of 1000 equals to 1 second. To execute a
function only once, after a specified number of milliseconds, we use the setTimeout()
method.
Example 17.1
<button onclick="myFunction()">Load Message</button>
<button onclick="myFunction2()">Stop</button></p>
<script>
function myFunction() {
var1=setInterval(function(){ alert("Welcome to JavaScript Tutorial"); }, 2000);
}
function myFunction2() {
clearInterval(var1);
}
</script>
145
Running this script produces a popup dialog that displays the message "Welcome to
JavaScript Tutorial" every two seconds. You can stop it by clicking the stop button.
Figure 16.1
You can also reference a function; Alert "Hello" every 3 seconds (3000 milliseconds):
var myVar;
function myFunction() {
myVar = setInterval(alertFunc, 3000);
}
function alertFunc() {
alert("Hello!");
}
Example 17.2 Displaying Current Time
Display the current time (the setInterval() method will execute the function once every 1
second, just like a digital watch):
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
146
The Output
Figure 17.1
17.2 The ClearInterval( ) Method
The clearInterval() method clears a timer set with the setInterval() method.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
The syntax is
clearInterval(id_of_setinterval)
Example 17.3
To run and stop and popup dialog
<button onclick="myFunction()">Run it</button><br> <button onclick="myFunction2()">Stop it</button> <script> var myVar; function myFunction() { myVar = setInterval(alertFunc, 2000); } function myFunction2() { clearInterval(myVar); } function alertFunc() { alert("Hello!"); } </script>
147
Example 17.4
In this example, the setInterval() method executes the setColor() function once every 300
milliseconds, which will toggle between two background colors. The stopColor function
will stop the animation using the clearInterval method.
<button onclick="stopColor()">Stop Toggling</button> <script> var myVar = setInterval(function(){ setColor() }, 300); function setColor() { var x = document.body; x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow"; } function stopColor() { clearInterval(myVar); } </script>
Example 17.5
This script creates a clock. It is stopped by using the clearInterval method
<p>A script on this page starts this clock:</p> <p id="demo"></p> <button onclick="myStopFunction()">Stop time</button> <script> var myVar = setInterval(function(){ myTimer() }, 1000); function myTimer() { var d = new Date(); var t = d.toLocaleTimeString(); document.getElementById("demo").innerHTML = t; } function myStopFunction() { clearInterval(myVar); } </script>
148
Chapter 18 Interesting Examples
18.1 Animated Digital Dice
We can create an animated digital dice using the setInterval() method to be used as
the timer. Next, we create a JavaScript function rolldice()to generate random
integers. A combination of the floor method and the random method is to generate
random integers from 1 to 6 using the following syntax:
Math.floor( 1 + Math.random() * 6 )
Besides that, we create a JavaScript function AniDice ()to set the interval of rolldice()
to 20 milliseconds.
We use the <div> element to define the size of the digital dice. The id="dice' is to
replace the default number 1 with the random numbers.
The HTML is as follows:
<div style="border:4px solid blue; width:100px; height:100px text-align:center;padding:0">
<h1 id="dice" style="font-size:300%">1</h1></div>
<button onclick="AniDice()">Roll Dice</button>
<button onclick="stopDice()">Stop</button>
The JavaScript is as follows:
<script>
function AniDice()
{MyVar=setInterval(rolldice,20)
}
149
function rolldice()
{ var ranNum = Math.floor( 1 + Math.random() * 6 );
document.getElementById("dice").innerHTML = ranNum;
}
function stopDice()
{clearInterval(MyVar);}
</script>
Click on the 'Roll Dice' button to roll the dice.
Figure 18.1
18.2 Animated Graphical Dice
In this example, we will create an animated dice that changes rapidly when we click the
roll dice button. In order to create an animated dice, first of all, you need to design 6
images of a dice that represent 1, 2, 3,4, 5 and 6, Next, we need to create a JavaScript
function that can generate an animated dice.
To create animation, we use the setInterval method, the syntax is as follows:
myVariable=setInterval(myfunction, time interval)
The setInterval method runs a function at a certain time interval in milliseconds. For
example, a time interval of 1000 equals to 1 second.
We use the following syntax to create 6 random numbers:
ranNum = Math.floor( 1 + Math.random() * 6 );
150
We also use the following statement to load the first image as default image.
<img id="die" src="1.jpg" width="50" height="50">
The id is important as we shall use it to load other images when the animation starts, as
shown in the following code:
var ranNum = Math.floor( 1 + Math.random() * 6 );
var dice = document.getElementById("die");
dice.src=ranNum+".jpg";
}
ranNum will be a random integer ranging from 1 to 6. By using the src property and
combining ranNum+".jpg", we will be able to load the 6 images randomly.
The JavaScript
<html>
<head>
<title>JavaScript Graphical Dice Function</title>
</head>
<body>
<img id="die" src="1.jpg" width="50" height="50">
<button onclick="AniDice()">Roll Dice</button>
<button onclick="stopDice()">Stop</button>
<script>
function AniDice()
{myVar=setInterval(rolldice,20)
}
function rolldice()
{
var ranNum = Math.floor( 1 + Math.random() * 6 );
151
var dice = document.getElementById("die");
dice.src=ranNum+".jpg";
}
function stopDice()
{clearInterval(myVar);}
</script>
</body>
</html>
The Output UI
Figure 18.2
18.3 Animated Butterfly
We can create an animated butterfly that is flapping its wings using the setInterval()
method.
In this example, we used eight images of a butterfly that flaps its wings at a different
stage.
Name the images files as bfly1.gif, bfly2.gif, bfly3.gif, bfly4.gif,
bfly5.gif, bfly6.gif, bfly7.gif, bfly8.gif.
We shall load the images starting from image1 till image 8 and then repeat the sequence
again at a regular interval set by using the setInterval() method.
152
Besides that, we declared a global variable i and assign an initial value 0 to it, then use
the iteration i+=1 to increase its value one at a time. We reset the value of i back to 0
after its value exceeds 9 using the if statement.
We use the following statement to load the images:
var dice = document.getElementById("die");
dice.src="bfly"+i+".gif";
The full script is as follows:
var i=0
var step;
function start(){
myVar=setInterval(rolldice,100);
}
function rolldice(){
i+=1
if (i<9){
var dice = document.getElementById("die");
dice.src="bfly"+i+".gif";
}
else
{i=0}
}
function stop()
{clearInterval(myVar)}
</script>
153
The output UI
Figure 18.3
18.4 The Countdown Timer
We can create a countdown timer using the setInterval method. We set the interval of
the timer to 1000 which means 1 second. Besides that, we shall use the if statement to
decrease the counter by 1 after each cycle.
<script>
function countdown(){
var counter = 10;
var newYearCountdown = setInterval(function(){
document.getElementById("demo").innerHTML = counter;
counter--
if (counter ==-1) {
document.getElementById("demo").innerHTML = "HAPPY NEW YEAR!!";
154
clearInterval(newYearCountdown);
}
}, 1000);
}
</script>
The Output
Figure 18.4
18.5 Basic Calculator
This is a simple JavaScript calculator that adds two numbers. In this example, we create
a JavaScript function RandomFn() that loads two random numbers when the web page is
loaded in the browser or when the user clicks the Next button.
function RandomFn() {
document.getElementById("num1").innerHTML =
parseInt(Math.random()*100);
document.getElementById("num2").innerHTML =
parseInt(Math.random()*100);
}
Next, we create a function that adds two numbers.
function myFunction() {
var number1=document.getElementById('num1').innerHTML ;
155
var number2=document.getElementById('num2').innerHTML;
var sum=parseInt(number1)+parseInt(number2);
document.getElementById('ans').textContent="The sum of two numbers=
"+sum;
}
The following is the complete code
<html>
<head>
<title>Kid Math</title>
</head>
<h3>Addition of Two Numbers</h3>
<body onload="RandomFn()">
<p>Number 1: <b id="num1"></b></p>
<p>Number 2: <b id="num2"></b></p>
<p id="ans">Calculate the sum of two numbers</p><br>
<input type="button" value="Calculate" onclick="myFunction()"><br><br>
<input type="button" value="Next Question" onclick="RandomFn()">
<script>
function myFunction() {
var number1=document.getElementById('num1').innerHTML ;
var number2=document.getElementById('num2').innerHTML;
var sum=parseInt(number1)+parseInt(number2);
document.getElementById('ans').textContent="The sum of two numbers=
"+sum;
}
function RandomFn() {
document.getElementById("num1").innerHTML =
parseInt(Math.random()*100);
document.getElementById("num2").innerHTML =
parseInt(Math.random()*100);
}
</script>
156
</body>
</html>
Figure 18.5
18.6 Math Drill
We can modify the basic calculator and make it into an online interactive math drill for
kids. First, create the following JavaScript and save it as kidmath2.js
function myFunction() {
var number1;
var number2;
var answer;
var message
number1=document.getElementById('num1').innerHTML ;
number2=document.getElementById('num2').innerHTML;
answer=document.getElementById('ans1').value;
var sum=parseInt(number1)+parseInt(number2);
if (answer==sum)
{message="Correct";}
else
{message="Incorrect";}
157
document.getElementById('ans').textContent=message;
}
Next, we add the following line in this web page to launch the JavaScript when this web
page is loaded in the browser.
<script type="text/javascript" src="kidmath2.js"></script>
We also added the following HTML elements to place two buttons, a textbox and a
container for displaying the message on the web page.
<b id="num1">x</b>+<b id="num2">y</b>= <input type="text" size="5"
id="ans1">
<input type="button" value="Start" onclick="RandomFn()">
<input type="button" value="Check Answer" onclick="myFunction()">
<input type="button" value="Next Question" onclick="RandomFn()">
<h3 id="ans"><h3>
Besides that, we also add the following function RandomFn to generate the random
numbers.
<script>
function RandomFn() {
document.getElementById("num1").innerHTML = parseInt(Math.random()*100);
document.getElementById("num2").innerHTML = parseInt(Math.random()*100);
document.getElementById("ans1").value = " ";
}
</script>
158
Click the start button to start the drill then enter your answer in the box. Next, check the
answer whether it is correct or incorrect.
Figure 18.6
18.7 Pythagoras Theorem The Pythagoras Theorem is used to solve problems related to the length of the sides of a
triangle. The formula is
AB2+AC2=BC2
AB is the opposite side, AC is the adjacent and BC is the hypotenuse of a triangle ABC.
We shall create a JavaScript application to deal with problems related to the Pythagoras
Theorem. In this application, we shall randomly generate the length of the opposite side
and the length of the adjacent side of a triangle. The user can then click on the Calculate
Hypotenuse button to find the answer.
We use the Math function Math.pow(n,2)to find the square of a and b. The sqrt
function is to find the square root of a number. We use the toFixed function to convert
the resulting answer into a number with 2 decimal places.
The JavaScript is as follows:
159
function Calhypo(a,b){
var hypo=Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
return hypo;
}
function Cal_hypo(){
var x=parseInt(document.getElementById("adjacent").innerHTML);
var y=parseInt(document.getElementById("opposite").innerHTML);
var z=Calhypo(x,y);
var c=z.toFixed(2);
document.getElementById('ans').textContent="The Length of hypotenuse is= "+c;
}
Save the above script as pythagoras.js
The HTML is as follows:
<html>
<head>
<title>Pythagoras Theorem</title>
</head>
<body onload="RandomFn()">
<h1>Pythagoras Theorem</h1>
<p>Length of adjacent side a=<b id="adjacent"></b></p>
<p>Length of opposite side b=<b id="opposite"></b></p>
<P id="ans">The Length of hypotenuse c is</p>
<input type="button" value="Calculate hypotenuse" onclick="Cal_hypo()"><br><br>
<input type="button" value="Next Question" onclick=" lRandomFn();">
160
<script>
function RandomFn() {
document.getElementById("adjacent").innerHTML =
parseInt(Math.random()*9+1);
document.getElementById("opposite").innerHTML =
parseInt(Math.random()*9+1);
}
</script>
<script type="text/javascript" src="pythagoras.js"></script>
</body>
</html>
The output
Figure 18.7
161
18.8 Quadratic Graph
To draw a quadratic curve, we use the quadraticCurve() method. However, we need
to combine the quadraticCurve() method with the beginPath() and moveTo()
methods in order to draw a quadratic curve. The beginPath() and moveTo() methods
define the starting point of the quadratic curve. The quadraticCurve() method is to define
the lowest point to the end point of the quadratic curve. The syntax of the
quadraticCurve() method is
quadraticCurveTo(x1, y1, x2, y2)
*(x1, y1) is the lowest point. *(x2, y2) is the end point.
Before we can draw a quadratic curve, we need to create a canvas by defining its width
and height, using the <canvas> tag. Please note that <canvas> is an HTML5 element
that might not be supported by certain versions of browsers.
The JavaScript is to draw a quadratic curve :
<canvas id="myCanvas" style="border: 1px solid #d3d3d3;" width="250"
height="300">
</canvas>
<input type="button" value="Draw Curve" Onclick="DrawCurve()">
<script>
function DrawCurve()
{var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(90, 400, 200, 20);
ctx.stroke();
}
162
</script>
Please click on the Draw Curve button to view the output.
Figure 18.8
The next example let the user input the starting point as well as the lowest point and the
ending point. We also add a clearRect method to clear the canvas. The syntax of the
clearRect is
ctx.clearRect(0, 0,canvas.width, canvas.height)
* (0,0) is the coordinates of the origin that refer to the upper top-left corner of the canvas.
Besides that, we also create a canvas with dark blue background. In addition, we want to
draw white line so we add the code ctx.strokeStyle = 'white'.
<canvas id="myCanvas" style="border: 1px solid #d3d3d3;" width="250"
height="300">
</canvas>
<input type="button" value="Draw Curve" Onclick="DrawCurve()">
<input type="button" value="Clear Graph" Onclick="ClearCurve2()">
163
function DrawCurve()
{
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");
var a=document.getElementById("a").value;
var b=document.getElementById("b").value;
var x1=document.getElementById("x1").value;
var y1=document.getElementById("y1").value;
var x2=document.getElementById("x2").value;
var y2=document.getElementById("y2").value;
ctx.strokeStyle = 'white';
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(x1,y1,x2,y2);
ctx.stroke();
}
</script>
<script>
function ClearCurve2(){
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0,350, 300);
}
</script>
The output is shown in Figure 18.9
164
Figure 18.9
18.9 Music Player
You can create a music player that can play music or an audio file such as mp3. In order
to play an audio file in a browser, you need to use the <audio> element. The audio object
is new in HTML5. The <audio> element has a number of properties, one of them is
controls. The controls property sets or returns whether an audio should have controls
displayed like play, pause and more. We also need to use the <source> tag to reference
the source of an audio file, the syntax is as follows:
165
<audio controls>
<source src="music.ogg" type="audio/ogg">
<source src="music.mp3" type="audio/mpeg">
</audio>
The <source> tag has to be used together with the <audio> element. Next, you can
create a Play button using the play() method to start playing the music or audio file. The
syntax is
myAudioObject.play()
It is often used together with the pause() method. The following is the script that can play
a music file.
<audio controls id="music">
<source src="mj.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<p>Click the buttons to play or pause the music.</p>
<button onclick="play()" type="button">Play </button>
<button onclick="pause()" type="button">Pause</button>
<script>
var myMusic= document.getElementById("music");
function play() {
myMusic.play();
}
function pause() {
myMusic.pause();
}
</script>
166
The UI
Figure 18.10
18.10 Video Player
To create a video player that can play video files on a web page, you need to use the
<video> element in HTML5 to define the video screen size and the <source> element
to refer to the source of the video file. Besides that, you have to assign an id to the video
source so that the Javascript function can refer to it.
For the JavaScript, we use the document.getElementById to refer to the video clip. To
play the video clip, we use the play method and to pause the video clip, we use the
pause method. The Javascript is shown overleaf.
<html>
<body>
<button onclick="playVideo()" type="button">Play</button>
<button onclick="pauseVideo()" type="button">Pause</button><br>
<video id="myVid" width="400" height="200">
<source src="beach.mp4" type="video/mp4">
</video>
<script>
var myVideo = document.getElementById("myVid");
function playVideo() {
167
myVideo.play();
}
function pauseVideo() {
myVideo.pause();
}
</script>
</body>
</html>
Figure 18.11