Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

JavaScript Notes

JavaScript is a lightweight, interpreted programming language designed for creating network-centric applications, integrated with HTML and Java. It offers advantages such as less server interaction, immediate feedback, and increased interactivity, but has limitations like lack of file handling and multithreading. The document also covers JavaScript syntax, development tools, language elements, data types, and operators.

Uploaded by

sirodaniel48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript Notes

JavaScript is a lightweight, interpreted programming language designed for creating network-centric applications, integrated with HTML and Java. It offers advantages such as less server interaction, immediate feedback, and increased interactivity, but has limitations like lack of file handling and multithreading. The document also covers JavaScript syntax, development tools, language elements, data types, and operators.

Uploaded by

sirodaniel48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

JavaScript

 JavaScript is a lightweight, interpreted programming language with object-oriented


capabilities.
 Designed for creating network-centric applications.
 Complementary to and integrated with Java.
 Complementary to and integrated with HTML.
 Open and cross-platform.
 The ECMA-262 Specification defined a standard version of the core JavaScript
language.

Client-Side JavaScript

 Client-side JavaScript is the most common form of the language.


 The script should be included in or referenced by an HTML document for the code to be
interpreted by the browser.
 It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
 The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.
 JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.

Advantages of JavaScript

The merits of using JavaScript are:

 Less server interaction:


 You can validate user input before sending the page off to the server.
 This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors:
 They don't have to wait for a page reload to see if they have forgotten to enter
something.
 Increased interactivity:
 You can create interfaces that react when the user hovers over them with a mouse
or activates them via the keyboard.
 Richer interfaces:
 You can use JavaScript to include such items as drag-and drop components and
sliders to give a Rich Interface to your site visitors.

1
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
 Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
 JavaScript cannot be used for networking applications because there is no such
support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.

JavaScript Development Tools


 One of major strengths of JavaScript is that it does not require expensive
development tools.
 You can start with a simple text editor such as Notepad.
 Since it is an interpreted language inside the context of a web browser, you don't even
need to buy a compiler.

Various vendors have come up with very nice JavaScript editing tools. Some of these tools are:
 Microsoft FrontPage:
 Microsoft has developed a popular HTML editor called FrontPage.
 FrontPage also provides web developers with a number of JavaScript tools to
assist in the creation of interactive websites.
 Macromedia Dreamweaver MX:
 Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in
the professional web development crowd.
 It provides several handy prebuilt JavaScript components, integrates well with
databases, and conforms to new standards such as XHTML and XML.
 Macromedia HomeSite 5:
 HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that
can be used to manage personal websites effectively.

JavaScript – Syntax
 JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
 You can place the <script> tags, containing your JavaScript, anywhere within you
web page,
 but it is normally recommended that you should keep it within the <head>
tags.

2
 The <script> tag alerts the browser program to start interpreting all the text between these
tags as a script.
 A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>

The script tag takes two important attributes:


 Language: This attribute specifies what scripting language you are using.
 Typically, its value will be javascript.
 Although recent versions of HTML (and XHTML, its successor) have phased out
the use of this attribute.
 Type: This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
 So your JavaScript syntax will look as follows.
<script language="javascript" type="text/javascript">
JavaScript code
</script>

A simple JavaScript Code


 In this program an optional HTML comment is added to surround the JavaScript code.
 This is to save our code from a browser that does not support JavaScript.
 The comment ends with a "//-->".
 Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from
reading the end of the HTML comment as a piece of JavaScript code.
 Next, we call a function document.write which writes a string into our HTML
document.
 This function can be used to write text, HTML, or both.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>

3
Whitespace and Line Breaks
 JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
 You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.

Semicolons are Optional


 Simple statements in JavaScript are generally followed by a semicolon character, just as
they are in C, C++, and Java.
 JavaScript, however, allows you to omit this semicolon if each of your statements are
placed on a separate line.
 For example, the following code could be written without semicolons.

<script language="javascript" type="text/javascript">


<!--
var1 = 10
var2 = 20
//-->
</script>

 But when formatted in a single line as follows, you must use semicolons:
<script language="javascript" type="text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>

 Note: It is a good programming practice to use semicolons.

Case Sensitivity
 JavaScript is a case-sensitive language.
 This means that the language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of letters.

Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
 Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.

4
 JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.

Example
The following example shows how to use comments in JavaScript.

<script language="javascript" type="text/javascript">


<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

Warning for Non-JavaScript Browsers


 If you have to do something important using JavaScript, then you can display a
warning message to the user using <noscript> tags.
 You can add a noscript block immediately after the script block as follows:

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>

 Now, if the user's browser does not support JavaScript or JavaScript is not enabled,
then the message from<noscript>--- </noscript> will be displayed on the screen.

5
JavaScript – Placement

 There is a flexibility given to include JavaScript code anywhere in an HTML document.


 However the most preferred ways to include JavaScript in an HTML file are as follows:
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.

JavaScript in <head>...</head> Section

 If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows.
 Example:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello( )

{
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />

</body>
</html>

This code will produce the following results:

Click here for the result

Say Hello

6
JavaScript in <body>...</body>Section

 If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document.
 In this case, you would not have any function defined using JavaScript.
 Example:

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

This code will produce the following results:

Hello World

JavaScript in <body> and <head> Sections

 You can put your JavaScript code in <head> and <body> section altogether as
follows.

<html>
<head>
<script type="text/javascript">
<!--
function sayHello()

{
alert("Hello World")
}
//-->
</script>
</head>
<body>
7
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

This code will produce the following result.

HelloWorld
Say Hello

JavaScript in External File

 There are cases where you can reuse identical JavaScript code on multiple pages of
a site.
 You are not restricted to be maintaining identical code in multiple HTML files.
 The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files.
 Example of how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.

<html>
<head>
<script type="text/javascript" src="filename.js" > </script>
</head>
<body>
.......
</body>
</html>

 To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.
 For example, you can keep the following content in filename.js file and then you
can use sayHello function in your HTML file after including the filename.js file.

function sayHello() {
alert("Hello World")
}

8
JavaScript Language Elements

 JavaScript language contains the following elements:


 Variables
 Operators
 Expressions
 Statements
 Objects
 Functions and methods

Variables

 Variables are used to hold data.


 A JavaScript identifier:
 Starts with a letter or underscore, and
 Is followed by letters, underscore or digits
 JavaScript is a case-sensitive language

 Scope: The scope of an identifier is either


 Global – An identifier that is accessible anywhere on the page
 Local – Is accessible only within the function it is declared within
 Example:

<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( )
{
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>

9
JavaScript Reserved Words

 A list of all the reserved words in JavaScript are given in the following table.
 They cannot be used as JavaScript variables, functions, methods, loop labels, or any
object
names.

abstract else Instanceof


switch
boolean enum int
synchronized
break export interface
this
byte extends long
throw
case false native
throws
catch final new
transient
char finally null
true
class float package
try
const for private
typeof
continue function protected
var
debugger goto public
void
default if return
volatile
delete implements short
while
do import static
with
double in super

Data Types
There are six data types in JavaScript :

 Numbers – Integer or floating point numbers


 Booleans – Either true/false or a number (0 being false) can be used for boolean values
 Strings – Sequence of characters enclosed in a set of single or double quotes
 Objects – Entities that typically represents elements of a HTML page
 Null – No value assigned which is different from a 0
 Undefined – Is a special value assigned to an identifier after it has been declared but
before a value has been assigned to it

JavaScript is a dynamically typed language.

 The data type of the identifier is not assigned when the identifier is declared.
 When a value is assigned to the identifier the identifier takes on that type.

10
 The data type of the variable is not important until an operator is applied to the variable.
 The behavior of the operator is dependent of the data type being acted upon.
 For example:
var name = “Sally”
name = 34
 The string, Sally, is first assigned to the variable.
 Next, the integer 34 is assigned to the variable.
 Both are legal but usage of the identifier is inconsistent.
 It is better if we are consistent when assigning a data type to a variable.
 This leads to less confusing code.

Converting Between Data Types

 There are a number of techniques for converting between data types.


 To convert from a string several parse and other functions are available.
 parseFloat – Converts a string to a float
 parseInt – Converts a string to an integer
 Number – Converts a string to a number
 The last example below uses an arithmetic expression to implicitly convert the string to a
number.

<html>
<head>
<title>JavaScript Data Conversion</title>
<script language="JavaScript 1.2">
<!--
document.write("<br>parseFloat - " + parseFloat('77.3'));
document.write("<br>parseInt - " + parseInt('77'));
document.write("<br>parseInt - " + parseInt('123.45'));
document.write("<br>Number - " + Number("2.34"));
document.write("<br>Implicit Conversion - " + ("2.34"-1));
//-->
</script>
</head>
<body>
</body>
</html>

11
 A number can be converted to a string or Boolean using the String and Boolean
functions.

<html>
<head>
<title> JavaScript Data Conversion </title>
<script language="JavaScript 1.2">
document.write("<br> String - " + String(2.34));
document.write("<br> Boolean - " + Boolean(2.34));
</script>
</head>
<body>
</body>
</html>

JavaScript – Operators

JavaScript supports the following types of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

12
Arithmetic Operators

JavaScript supports the following arithmetic operators:


Assume variable A holds 10 and variable B holds 20, then:

S. No. Operator and Description


+ (Addition)
1 Adds two operands
Ex: A + B will give 30
- (Subtraction)
2 Subtracts the second operand from the first
Ex: A - B will give -10
* (Multiplication)
3 Multiply both operands
Ex: A * B will give 200
/ (Division)
4 Divide the numerator by the denominator
Ex: B / A will give 2
% (Modulus)
5 Outputs the remainder of an integer division
Ex: B % A will give 0
++ (Increment)
6 Increases an integer value by one
Ex: A++ will give 11
-- (Decrement)
7 Decreases an integer value by one
Ex: A-- will give 9

 Note: Addition operator (+) works for Numeric as well as Strings.


 e.g. "a" + 10 will give "a10".
 Example: The following code shows how to use arithmetic operators in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var a = 33;

13
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>

14
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
Set the variables to different values and then try...

Comparison Operators

S.No Operator and Description


== (Equal)
Checks if the value of two operands are equal or not, if yes, then
1
the condition becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values
2
are not equal, then the condition becomes true.
Ex: (A != B) is true.
> (Greater than)
Checks if the value of the left operand is greater than the value of
3
the right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than the value of the
4
right operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to
5 the value of the right operand, if yes, then the condition becomes
true.
Ex: (A >= B) is not true.
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the
6
value of the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

15
Example

 The following code shows how to use comparison operators in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

16
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false

(a <= b) => true


Set the variables to different values and different operators and then try...

Logical Operators

 JavaScript supports the following logical operators:


 Assume variable A holds 10 and variable B holds 20, then:

S.No Operator and Description


&& (Logical AND)
1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
3
Logical NOT operator will make it false.
Ex: ! (A && B) is false.

Example

 Try the following code to learn how to implement Logical Operators in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);

17
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...

Assignment Operators

 JavaScript supports the following assignment operators:

1 Ex: C = A + B will assign the value of A + B into C


+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the
2
left operand.
Ex: C += A is equivalent to C = C + A
-= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result
3
to the left operand.
Ex: C -= A is equivalent to C = C - A
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result
4
to the left operand.
Ex: C *= A is equivalent to C = C * A

18
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to
5
the left operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left
6
operand.
Ex: C %= A is equivalent to C = C % A

Example

 Try the following code to implement assignment operator in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a += b) => ");
result = (a += b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

19
document.write("Value of a => (a %= b) => ");
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

Conditional Operator (? :)

 The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.

S.No Operator and Description


? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y

Example

 Try the following code to understand how the Conditional Operator works in
JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;

20
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");

result = (a < b) ? 100 : 200;


document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

typeof Operator

 The typeof operator is a unary operator that is placed before its single operand,
which can be of any type.
 Its value is a string indicating the data type of the operand.
 The typeof operator evaluates to "number", "string", or "boolean" if its operand is a
number, string, or boolean value and returns true or false based on the evaluation.
 Here is a list of the return values for the typeof Operator.

Type String Returned by typeof


Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"

21
Example

 The following code shows how to implement typeof operator.

<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);

//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...

22
Message Boxes

Alert Message Box


The alert message box displays a simple message.
Example: alert('This is an alert Dialog');

Confirm Dialog Box


The confirm dialog box displays a confirm type message and then either returns a true or false
value depending on which button is pressed.

Example:
var result = confirm("This is a confirm Dialog");
document.write(result);

Prompt Dialog Box

 The prompt dialog box provides a way of getting input from the user.
 The prompt function has two arguments.
 The first is the prompt message and
 the second is a default value if any.
 Example:
var result = prompt("Enter Your Name","");
document.write(result);
23
Control Structures

The following control structures are supported in JavaScript:

1. Selection
2. Iteration

Selection Control structures

These are composed of

1. if structure
2. if …else
3. switch

if statement

 This a one way decision structure


 Example:

var age = prompt("Enter your age");


if (parseInt(age <18){
alert("You are a youth"); }

if...else and else if statements

 if...else statements
 These allow a block of statements to be executed if the tested condition is true and
 another block of statements to be executed if the tested condition is false
 Example:
var age = prompt("Enter your age");
if (parseInt(age <18){
alert("You are a youth"); }
else{
alert("You are an adult"); }

24
 else if statements
 These allow multiple statements to be executed if the tested condition is true
 Example:
var grade
var marks = prompt("Enter marks");
parseInt(marks)
if (marks< 40){
grade = ‘F’;
alert(grade); }
else if (marks< 50){
grade = ‘D’;
alert(grade); }
else if (marks< 60){
grade = ‘C’;
alert(grade); }
else if (marks< 70){
grade = ‘B’;
alert(grade); }
else if (marks< =100){
grade = ‘A’;
alert(grade); }
else {
alert(“The grade is undefined”); }

switch statements

 These allow multiple decision making based on a certain case constant


 Example: Activities to be performed in each week day

var dayOfWk = prompt(“Enter day of the week”);

switch(dayOfWk) {
case “Sat” :
alert("Go to church");
break;
case "Sun" :
alert("Clean the Compound");
break;
case "Mon" :
alert("Visit sick people in Kisumu Hospitals");
break;

25
case “Tue” :
alert("Supervise operations in Kenyatta Hospital");
break;
case “Wed” :
alert("Visit Dadaab refugee camp");
break;
case “Thu” :
alert("Attend to patients in Cost general Hospital");
break;
case “Fri” :
alert("Give report to ministry of Health");
break;

default :
alert("No defined role");
}

Iteration Control structures

These are composed of

1. while
2. do…while
3. for

while loops

 These enables a block statements to be executed if a certain condition is true


 The evaluation condition is tested at the beginning of the loop
 Example:
var i = 0;
while (i <= 3) {
alert(i);
i++;
}

26
do...while loops

 These enables a block statements to be executed if a certain condition is true


 The evaluation condition is tested at the end of the loop
 Example:
var i = 0;
do {
alert(i);
i++;
} while (i <= 3)

for loop

 These enables a block statements to be executed if a certain condition is true


 Example:
for (var i = 0; i <= 3; i++) {
alert(i);
}

Functions

 A function is a block of JavaScript code that does the same thing again and again,
whenever you invoke its name.
 It saves you repetitive coding and makes your code easier to understand.
 Example:
On your website, suppose there are several pages where you want to display an alert that
tells the user the current time. (let us use 24-hour time)

var now = new Date();


var theHr = now.getHours();
var theMin = now.getMinutes();
alert("time: " + theHr + ":" + theMin);
 You could write this block of code over and over again, every time you need it.
 Or you could write it once as a function, naming it, say, tellTime.
 After that, this is the only code you'll need in order to make the whole block execute:
tellTime();
 Whenever JavaScript sees that short statement, the time-telling block executes.

27
 The function can be defined as follows:
function tellTime( ) {
var now = new Date();
var theHr = now.getHours();
var theMin = now.getMinutes();
alert("Current time: "+ theHr + ":" + theMin);
}

 The time-telling code—the code that creates the Date object, extracts the time, formats it,
and displays an alert.

Calling a function

 For a function to perform its task, it must be called.


 A function is called using its name
 If a function has parameters, then the arguments corresponding to the number of
parameters must be passed to it.
 Example of HTML code with function call:

<html>
<head> <title> Function Demo3 </title>
<script type="text/javascript" >
<!--
function tellTime( ) {
var now = new Date();
var theHr = now.getHours();
var theMin = now.getMinutes();
alert("Current time: "+ theHr + ":" + theMin);
}
//-->
</script>
</head>
<body>
<script>

28
<!--
document.write(tellTime());
//-->
</script>
</body>
</html>

 Example of calling a function with parameters

<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript" >
<!--
function multiply(num1, num2) {
return num1*num2;
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write(multiply(2,4));
//-->
</script>
</body>
</html>

29
Arrays

 An array is used to store a collection of data under one name.


 In JavaScript, an array can contain data items of different data types.
 Data items in an array are stored in indexes
 The first index in an array is 0
 An Array is an object with the constructor Array()

Creating Arrays

 An array must have a valid name just like a variable


 Array is created from the Array() constructor using the keyword new as follows:
 var firstArray = new Array();
var secondArray = new Array("red", "green", "blue");
var thirdArray = new Array(5);

 Alternatively, arrays can be created as follows:


var firstArray = [];
var secondArray = ["red", "green", "blue"];
var thirdArray = [,,,,];
 In the third declaration, the given literal has four commas, but the values they separate
seem to be missing.
 The interpreter treats this example as specifying five undefined values and sets
the array‘s length to 5 to reflect this.
 Sometimes you will see a sparse array with such a syntax:
var fourthArray = [,,35,,,16,,23,];
 Fortunately, most programmers stay away from this last array creation method, as it is
troublesome to count numerous commas.

Accessing Array Elements

 Accessing the elements of an array is done using the array name with square brackets and
a value.
 For example, we can define a three-element array like so:
var myArray = [1,51,68];
 Given that arrays in JavaScript are indexed beginning with zero, to access the first
element we would specify myArray[0].

30
 The following shows how the various elements in the last array could be accessed:
var x = myArray[0];
var y = myArray[1];
var z = myArray[2];
 However, you need to be careful when accessing an element of an array that is not set.
 For example,
alert(myArray[35]);
 results in the display of an undefined value, since this array element is obviously
not set.
 However, if we wanted to set this array element, doing so is quite straightforward.

Adding and Changing Array Elements

 The nice thing about JavaScript arrays, unlike those in many other programming
languages, is that you don‘t have to allocate more memory explicitly as the size of the
array grows.
 For example, to add a fourth value to myArray, you would use
myArray[3] = 57;
 You do not have to set array values contiguously (one after the other), so
myArray[11] = 28;
 is valid as well.
 However, in this case you start to get a sparsely populated array, as shown by the
dialog here that displays the current value of myArray

31
Modifying the values of an array

 To change the second value of the array, just assign it like this:
myArray[1] = 101;

Removing Array Elements

 Array elements can be removed using the delete operator.


 This operator sets the array element it is invoked on to undefined but does not change the
array‘s length (more on this in a moment).
 For example:
var myColors = ["red", "green", "blue"];
delete myColors[1];
alert("The value of myColors[1] is: " + myColors[1]);

The length Property

 The length property retrieves the index of the next available (unfilled) position at the end
of the array.
 Even if some lower indices are unused, length gives the index of the first available slot
after the last element.
 Consider the following:
var myArray = new Array( );
myArray[1000] = "This is the only element in the array";
alert(myArray.length);

32
Getting the current date and time

 Your webpage includes a notice telling the user the current local date and time in his
particular time zone.
 JavaScript produces this using the statement
var rightNow = new Date();
 The statement above creates a Date object.
 This will show:
 Day of week, Month, Date, Year, Hours(24 – Hours format), Minutes, Seconds,
Milliseconds, Offset from Greenwich Mean Time, Time zone
 JavaScript gets this information from the user's computer.
 It is only as accurate as the computer's date and time settings.
 For example, if the user just moved from the U.S. West Coast to the U.S. East
Coast and hasn't reset the time zone on his computer, the computer will still be on
Pacific Time.
 The Date object, too, will be on Pacific Time.
 The Date object may resemble a string, but it isn't one.
 For example, you can't use methods on it like
 charAt, indexOf, or slice.
 If you need the Date object to be a string, you can convert it to one the same way you
convert a number to a string.
 Example:
var dateString = rightNow.toString();
 The code above converts the Date object represented by the variable rightNow to a
string and assigns the string to the variable dateString.
 Most of the time, you'll just want to extract some of the information from the Date object
without converting it to a string.
 The following code creates a new Date object, assigns it to the variable rightNow,
extracts the day of the week, and assigns the day of the week to the variable theDay.
var rightNow = new Date();
var theDay = rightNow.getDay();
 When you extract the day of the week from the object Object, it's represented as a
number.
 Days are designated by a number from 0 for Sunday through 6 for
Saturday.
 This means that you'll need a bit of code to convert it back into a day name like
"Mon."

33
 Example:
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var now = new Date();
var theDay = now.getDay();
var nameOfToday = dayNames[theDay];

Here's what's going on:


1. Creates an array of days starting with "Sun" and assigns it to dayNames.
2. Creates a new Date object and assigns it to now.
3. Extracts the day of the week as a number and assigns it to theDay.
4. Uses the day number as an index to specify the correct array element, i.e. the
day name.

Extracting parts of the date and time

Here's a summary of important methods for extracting pieces of the Date object.

Method Gets Range Example


getDay() Day the week 0-6 0 is Sunday
getMonth() Month 0-11 0 is January
getDate() Day of month 1-31 1 is 1st of month
getFullYear() Year 2015
getHours() Hour 0-23 0 is midnight
12 is noon
23 is 11 p.m.
getMinutes() Minute 0-59
getSeconds() Second 0-59
getMilliseconds() Millisecond 0-999
getTime() Milliseconds since midnight, January 1, 1970

The following extraction methods are considered

 getMonth() gives you not the spelled-out name of the month shown in the Date object,
but a number.
 The following code produces a month number ranging from 0 for January through
11 for December.
var d = new Date();
var currentMonth = d.getMonth()
 getDate gives you a number for the day of the month.

34
var dayOfMonth = d.getDate();
 getFullYear gives you a 4-digit number for the year.
 var currYr = d.getFullYear();
 getHours gives you a number from 0 through 23 corresponding to midnight through 11
p.m.
var currentHrs = d.getHours();
 getMinutes gives you a number from 0 through 59.
var currMins = d.getMinutes();
 getSeconds gives you a number from 0 through 59.
var currSecs = d.getSeconds()
 getMilliseconds gives you a number from 0 through 999.
var currMills = d.getMilliseconds();
 getTime gives you the number of milliseconds that have elapsed since midnight, Jan. 1,
1970.
var millsSince = d.getTime();

Specifying a date and time

Suppose you want to compute many days before the U.S. Social Security program goes broke.

 You can start with the estimated date.


 According to the system's trustees, the money will run out in 2035.
 This pin down an exact date.
 You can pick the middle of the year - June 30.
 Once you have that, constructing a day by day countdown is for JavaScript romp.

 The first step is to create a Date object for the current date and time:
1. var today = new Date();
 Next, you create a second Date object.
 But this time you specify the future date, June 30, 2035.
2. var doomsday = new Date("June 30, 2035");
 Next, you extract from both dates the milliseconds that have elapsed since the reference
date of January 1, 1970.
3. var msToday = today.getTime();
4. var msDoomsday = doomsday.getTime();
 You calculate the difference.
5. var msDiff = msDoomsday - msToday;
 Some simple math converts the milliseconds to days.
6. var dDiff = msDiff / (1000 * 60 * 60 * 24);

35
 The huge number created by the math inside the parentheses converts the milliseconds
into seconds (1000), minutes (60), hours (60), and days (24).
 You want a number that represents whole days, so you round down.
 The following statement rounds the number of days, which is probably a floating-point
number, down to an integer.
7. dDiff = Math.floor(dDiff);
 The whole thing can be condensed into something that looks more like production code
1. var msDiff = new Date("June 30, 2035").getTime() - new Date().getTime();
2. var daysTillDoom = Math.floor(msDiff / (1000 * 60 * 60 * 24));
 Line 1 subtracts the milliseconds since the reference date of the current moment from the
milliseconds since the reference date of June 30, 2035.
 Line 2 converts the milliseconds to days and rounds down.
 If the time is important, you can specify that as well.
 var d = new Date("July 21, 1983 13:25:00");
 Note the form used to specify the time:
 No comma after the date. 24-hour time.
 Colons separating hours, minutes, and seconds.

Changing elements of a date and time

 You can change individual elements of a Date object.


 Here's a summary:

Method Example Result


(Variable corresponding the
Date object is d)
setFullYear() d.setFullYear(2006); Year is 2006
setMonth() d.setMonth(6); Month is 6 (July)
setDate() d.setDate(6); Day of the month is 6
setHours() d.setHours(6); 6 a.m.
setMinutes() d.setMinutes(6); 6 minutes past the hpur
setSeconds() d.setSeconds(6); 6 seconds past the minute
setMilliseconds() d.setMilliseconds(6); 6 milliseconds past the second

 setFullYear sets the year of an existing Date object without changing any other element.
1. var d = new Date();
2. d.setFullYear(2001);
 Line 1 creates a new Date object for the current moment.

36
 Line 2 changes the year of the Date object to 2001, leaving all other elements of the Date
object intact.
 setMonth sets the month of an existing Date object without changing any other element.
1. var d = new Date();
2. d.setMonth(11);
 Line 1 creates a new Date object for the current moment.
 Line 2 changes the month of the Date object to 11 (December), leaving all other elements
of the Date object intact.
 setDate sets the day of the month of an existing Date object without changing any other
element.
1. var d = new Date();
2. d.setDate(15);
 Line 1 creates a new Date object for the current moment.
 Line 2 changes the date of the Date object to the 15th of the month, leaving all other
elements of the Date object intact.
 setHours sets the hours of an existing Date object without changing any other element.
1. var d = new Date();
2. d.setHours(13);
 Line 1 creates a new Date object for the current moment.
 Line 2 changes the hours of the Date object to the 13th hour (1 p.m.), leaving all other
elements of the Date object intact.
 setMinutes sets the minutes of an existing Date object without changing any other
element.
1. var d = new Date();
2. d.setMinutes(05);
 Line 1 creates a new Date object for the current moment.
 Line 2 changes the minutes of the Date object to 5 minutes after the hour, leaving all
other elements of the Date object intact.
 setSeconds sets the seconds of an existing Date object without changing any other
element.
1. var d = new Date();
2. d.setSeconds(55);
 Line 1 creates a new Date object for the current moment.
 Line 2 changes the seconds of the Date object to the 55 seconds after the minute, leaving
all other elements of the Date object intact.
 setMilliseconds sets the milliseconds of an existing Date object without changing any
other element.
1. var d = new Date();
2. d.setMilliseconds(867);

37
 Line 1 creates a new Date object for the current moment.
 Line 2 changes the milliseconds of the Date object to 867 milliseconds after the second,
leaving all other elements of the Date object intact.

JavaScript Events

 A good website is a responsive website.


 The user does something—clicks a button, moves the mouse, presses a key—and
something happens.
 JavaScript gives you many ways to respond to the user's needs.
 A few examples:
 The user clicks a button saying "Our Guarantee" and an alert displays spelling out
the guarantee.
 A page displays a "before" picture of a model. When the user mouses over the
picture, it is replaced by an "after" picture of her.
 The user has entered her email address in a form, and is about to type a comment.
When she moves the cursor from the email field to the comment field, JavaScript
checks to see if the email address is valid.
 In this case, it isn't - she's omitted ".com" at the end of the address.
 A message displays letting her know that she's entered an invalid email address.
 On an online shopping site, there's a picture of a black watch. Next to it is a drop-
down list asking the user to choose a color.
 When she chooses, the color of the watch in the picture changes to that color.
 All of these user actions—clicking a button, moving the mouse, moving from one field to
another in a form, selecting a different option - are known as events.
 JavaScript code that responds to an event - for example, displaying a guarantee or
swapping an image when the pointer hovers over it - is called an event handler.
 The oldest and most straightforward approach to event-handling is inline event-handling.
 When you're writing production code, this is not the best way to handle events. But it is
least abstract and easiest way to learn, and can serve as a stepping stone to more
advanced methods.
 The approach that's preferred by most professionals is the scripting
approach.
 Inline event-handling means that you combine bits of JavaScript with HTML markup.

38
Some of the events that are normally the result of some user actions are:

Event Meaning
onload Occurs when a window or frame has loaded
onunload Occurs when a document is removed from a window or frame
onclick The mouse is clicked on an element
ondblclick The double click event
onmousedown Mouse down event
onmouseup Mouse up event
onmouseover Mouse moves onto an element
onmousemove Mouse moves over an element
onmouseout Mouse leaves an element
onfocus Element receives focus
onblur Element loses focus
onkeypress Key press event
onkeydown Key is pressed down
onkeyup Key is released
onsubmit Submit button is pressed
onreset Form reset event occurs
onselect Some text in an element is selected
onchange Element loses focus and its value changes

Events: link

 Here's a line that displays a link and then displays an alert when the user clicks it.
 <a href="#" onClick="alert('Hi');">Click</a>
 When the user clicks this link, it behaves differently than normal hyperlinks.
 Instead of taking the user to another page, or to a named anchor on the same page, it
displays an alert
saying "Hi".
 When the user clicks the link, it goes nowhere, and instead executes a JavaScript
statement, in this case calling a function.
 When the user clicks the link, you don't want a new webpage to be loaded in this case, so,
instead of a URL, you place a # inside the quotation marks.
 This tells the browser to reload the current page.
 But there's a problem with the markup above.
 <a href="#" tells the browser to reload the page.

39
 This means that if the user has scrolled down to the link, the click, in addition to
running the JavaScript code, will scroll the page back to the top—an action you
don't normally want.
 prefer this approach:
 <a href="JavaScript:void(0)" onClick="alert('Hi');">Click</a>
 Now the click executes only a single JavaScript statement.
 But there is no limit to the number of JavaScript statements that you can enclose
in the quotation marks.
 An example to show this principle is: with this example.
 <a href="JavaScript:void(0)" onClick="var greet=’hi’; alert(greet);">Click</a>

Events: button

 Suppose that when the user clicks a button, an alert displays saying, "Hello world!"
 Here's the code.
 <input type="button" value="Click" onClick="alert('Hello world!');">
 The event handler is the same, whether you're coding a link or a button:
 onClick="alert('Hello world!');"
 But the beginning of the code is different:
 <input type="button" value="Click" onClick="alert('Hello world!');">
 Some people would argue that the button code should be enclosed in form tags, but it's
not absolutely necessary.
 As an HTML coder you know that you can use an image as a hot link.
 The markup would look something like this.
 <a href="summary-page.html"><img src="button-sum-pg.png"></a>
 You can also use an image to trigger an event.
 Example:
 <img src="button-greet.png" onClick="alert('Hello world!');"> Or,
 if you want to be more professional about it, you could have the event trigger a
function.
<img src="button-greet.png" onClick="greetTheUser();">

Events: mouse

 Suppose your page initially displays a "before" picture of a model.


 When the user mouses over the picture, it is replaced by an "after" picture.
 The markup that replaces the before picture with the after picture is:
 <img src="before-pic.jpg" onMouseover="src='after-pic.jpg'">
 You can use onMouseover event handling with other HTML elements, too.
40
 Example:
 <h1 onMouseover="alert('Be sure to get your shopping done today.');">World
Ends Tomorrow</h1>
 When the user mouses over the head, an alert displays.
 In the example above, you might prefer to call a function that displays the alert rather
than code the alert inline.
 Example:
 <a href="index.html" onMouseover="this.style.color='green';">Home Page</a>
 When the user mouses over the link, it turns green.
 In the next example, the paragraph expands to include more information when the user
hovers over it.
 <p id="loris" onMouseover="expand();">Slow Loris: Mouse over for more
info</p>
 When you want the image to revert to the original when the user mouses away
from the picture.
 You would combine the onMouseover event handler with the onMouseout event
handler as follows:
<img src="before-pic.jpg" onMouseover="src='after-pic.jpg'"
onMouseout="src='before-pic.jpg'">

Events: fields

 Suppose you have a text field for the user's email address.
 When the user clicks in the field to type her entry, the field turns yellow.
 This is the markup that makes it happen.
Email:<br>
<input type="text" size="30" onFocus="this.style.backgroundColor='yellow';">
 The keyword here is onFocus.
 It tells JavaScript to do something when the user clicks in the field.
 This markup handles both the onFocus and the onBlur events.
 Email:<br>
 <input type="text" size="30" onFocus="this.style.backgroundColor='yellow';"
onBlur="this.style.backgroundColor='white';">
 When the user clicks into the field, it turns yellow. When she clicks out of the
field, it reverts to white.
 A slightly more professional approach would be to call functions that accomplish the
same things.
 Email:<br>

41
 <input type="text" size="30" onFocus="makeFieldYellow();"
onBlur="makeFieldWhite();">

Reading field values

 Suppose you've included an email field in a form, and you've made it a required field.
 The form has a submit button that the user clicks to submit the information that he's
entered in the form.
 This is the markup that creates the form.
 <form>
Email:
<input type="text">
<input type="submit" value="Submit">
</form>
 The form markup has three elements:
1. The text "Email"
2. The text field for the user's email address
3. The submit button
 The email field can be given an id as follows:
<form>
Email:
<input type="text" id="email">
<input type="submit" value="Submit">
</form>
 Next, an event-handler can be added by using the keyword onSubmit:
<form onSubmit="checkAddress('email');">
Email:
<input type="text" id="email">
<input type="submit" value="Submit">
</form>
 Now, when the user clicks the submit button, the function checkAddress executes.
 Note that
 even though the action is a click on the submit button, the onSubmit event
handler is in the form tag, not in the submit button tag.
 That's because the submission is an event that applies to the whole form, not the
submit button.
 When the form is submitted, the function checkAddress looks to see if the user has
entered anything in the email field.
 If not, the function displays an alert reminding the user that the email address is required.

42
 In order to do this, the function needs a way to read what's in the email field.
 This is where the id that is added to the field comes in.
 Here's the code for the function.
1. function checkAddress(fieldId) {
2. if (document.getElementById(fieldId).value == "") {
3. alert("Email address required.");
4. }
5. }

 If there's no value in the email field, an alert displays telling the user that an email
address is required.
 Some coders prefer to put the value found in the field into a variable, like this.
1. function checkAddress(fieldId) {
2. var val = document.getElementById(fieldId).value;
3. if val == "") {
4. alert("Email address required.");
5. }
6. }

Setting field values

 Suppose the user has entered her ZIP code in a form field.
 You want to save her the trouble of entering the city and state.
 So when she clicks out of the field, you fill in the city field for her.
 Assume there are only three ZIP codes in the U.S. and also that the user will infallibly
enter one of these codes.
 For this example, the JavaScript code will fill in only the city
field, not the state.
 Here's the relevant markup for the form:
ZIP:<br>
<input type="text" id="zip" onBlur="fillCity();"><br>
City:<br>
<input type="text" id="city">
</form>
 When the user clicks out of the ZIP field, the onBlur event triggers the fillCity
function.
 This is the code.
1. function fillCity() {
2. var cityName;

43
3. var zipEntered = document.getElementById("zip").value;
4. switch (zipEntered) {
5. case "60608" :
6. cityName = "Chicago";
7. break;
8. case "68114" :
9. cityName = "Omaha";
10. break;
11. case "53212" :
12. cityName = "Milwaukee";
13. }
14. document.getElementById("city").value = cityName;
15. }
 This example shows that you can not only read a value in a field with
document.getElementById..., but can also "write" a value into a field.
 In this case, the function assigns the value found in the ZIP field to a variable.
 Then, using a switch statement, it matches the ZIP to a city name and assigns that name
to a second variable.
 Then, using the variable, it places the city name in the city field.

Reading and setting paragraph text

 Your webpage initially displays a picture of a little mammal known as the slow loris,
along with a single sentence:
Slow lorises are a group of several species of strepsirrhine primates which make
up the genus Nycticebus. Click for more.
 When the user clicks the link, the paragraph expands:
Slow lorises are a group of several species of strepsirrhine primates which make
up the genus Nycticebus. They have a round head, narrow snout, large eyes, and a
variety of distinctive coloration patterns that are species-dependent. The hands
and feet of slow lorises have several adaptations that give them a pincer-like grip
and enable them to grasp branches for long periods of time. Slow lorises have a
toxic bite, a rare trait among mammals.
 This is the markup.
<p id="slowLoris">
Slow lorises are a group of several species of strepsirrhine primates which make
up the genus Nycticebus.
<a href="javascript:void(0);" onClick="expandLoris();"><em>Click for

44
more.</em></a>
</p>
 An id is assigned to the paragraph, which will be used by the function. When the user
clicks the link, a function, expandLoris, is called.
 This is the function.
1. function expandLoris() {
2. var expandedParagraph = "Slow lorises are a group of several species of trepsirrhine
primates which make up the genus Nycticebus. They have a round head, narrow
snout, large eyes, and a variety of distinctive coloration patterns that are species
dependent. The hands and feet of slow lorises have several adaptations that give them
a pincer-like grip and enable them to grasp branches for long periods of time. Slow
lorises have a toxic bite, a rare trait among mammals.";
3. document.getElementById("slowLoris").innerHTML = expandedParagraph;
4. }
 Line 2 assigns the long version of the text to a variable. Then, identifying the paragraph
by its id,
 line 3 replaces the original content, the innerHTML, with the text stored in the variable.
 Almost anything, including HTML tags, can be inserted into the web page this way.
 For example, you could make this list appear on the page within, say, a div with the id
"lorisList".
1. Slow loris
2. Fast loris
3. Just-right loris
 This is the function that loads the list markup into the div, which has been given an id of
"lorisList".
1. function placeAList() {
2. var listToPlace = "<ol><li>Slow loris</li><li>Fast loris</li><li>Just-right
loris</li></ol>";
3. document.getElementById("lorisList").innerHTML = listToPlace;
4. }
 Line 2 assigns all the HTML for the list to a variable. Line 3 places the HTML into the
div that has been assigned the id "lorisList".
 You can use document.getElementById(element id).innerHTML to read as well as
"write" the contents of an element.
 For example, this function assigns whatever is in the paragraph, div, or other element
with the id "content" to the variable whatsThere.
1. function peekAtContent() {
2. var whatsThere = document.getElementById("content").innerHTML;
3. }

45
 Line 2 reads all the HTML within the element with an id of "content" and assigns it to the
variable whatsThere.
 If the element is, for example, a paragraph whose content is "
<em>Hello, Sailor!</em>" the variable whatsThere captures "<em>Hello, Sailor!</em>"

Manipulating images and text

 Your webpage displays a picture of a blobfish.


 The blobfish is a fascinating animal, but it's so ugly, some of your users go "Yuck."
 So you give them the option of making it disappear.
 When they click the image, it vanishes.
 You begin by giving the image an id.
 <img src="Blobfish.jpg" id="ugly"...
 Then you add an event handler.
 <img src="blobfish.jpg" id="ugly" onClick="makeInvisible();">
 You have a CSS class for invisibility.
.hidden {display:none;}
 The function called by the event handler gives the image a class of "hidden," so it
disappears.
1. function makeInvisible() {
2. document.getElementById("ugly").className = "hidden";
3. }

 When the function is called, it assigns the "hidden" class to the element with the id
"ugly."
 The image disappears.

Target all elements by tag name

 Suppose you want to give your users the option of doubling the size of the text in all the
paragraphs of the document.
 To accomplish this, you could give each paragraph an id.
 When the user clicks the Double Text Size button, a function would cycle through all the
paragraph ids and make the change.
 The function could upsize the font either by assigning a new class to each paragraph, with
the class specifying a larger font size, or it could assign the new style property directly,
like this:
 getElementById(the id).style.fontSize = "2em";

46
 An easier way to accomplish the same thing is to have the function say, "Find all the
paragraphs in the document and increase their size."
 This statement finds all the paragraphs and assigns them to a variable:
 var par = document.getElementsByTagName("p");
 The variable, par, now holds an array-like collection of all the paragraphs in the
document.
 Suppose that the body of the document comprises just three paragraphs.
 <p>This bed is too small.</p>
 <p>This bed is too big.</p>
 <p>This bed is just right.</p>
 par[0] is the first paragraph. par[1] is the second paragraph. par[2] is the third
paragraph.
 par.length is 3, the number of items in the collection.
 If you write...
 var textInMiddleParagraph = par[1].innerHTML;
...the variable textInMiddleParagraph is assigned "This bed is too big."
 If you write...
 par[1].innerHTML = "This SUV is too big.";
...the paragraph text changes to "This SUV is too big."
 Here's a loop that assigns a font family to all the paragraphs.
1. for (var i = 0; i < par.length; i++) {
2. par[i].style.fontFamily = "Verdana, Geneva, sans-serif";

 This statement makes a collection of all the images in the document and assigns it to the
variable pics.
 var pics = document.getElementsByTagName("img");
 This statement makes a collection of all the divs in the document and assigns it to the
variable divs.
 var divs = document.getElementsByTagName("div");
 This statement makes a collection of all the unordered lists in the document and assigns it
to the variable ulists.
 var ulists = document.getElementsByTagName("ul");

Target some elements by tag name

 This statement makes a collection of all the paragraphs in the document and assigns the
collection to the variable pars.
 var pars = document.getElementsByTagName("p");

47
 This statement "reads" the contents of the second element in the collection pars and
assigns the string to the variable textInMiddleParagraph.
 var textInMiddleParagraph = pars[1].innerHTML;

 Suppose you don't want a collection of all the paragraphs in the document.
 Suppose you want just a collection of all the paragraphs within a particular div. No
problem. Let's say the id of the div is "rules".
 Here's the code:
1. var e = document.getElementByID("rules");
2. var paragraphs = e.getElementsByTagName("p");

 Line 1 assigns the div with the id "rules" to the variable e.


 Line 2 makes a collection of all the paragraphs in the div and assigns the collection to the
variable paragraphs.
 Once the id of the target div has been assigned to a variable, for example e, you can
assemble a collection of all the paragraphs within that div.
 Instead of writing...
 document.getElementsByTagName("p");
...which would make a collection of all the paragraphs in the document,
 you write...
 e.getElementsByTagName("p");
...which makes a collection of all the paragraphs in the div.

 Suppose you have a table with a white background.


 When the user clicks a button, the cells turn pink.
 Here's the code:
1. var t = document.getElementById("table9");
2. var cells = t.getElementsByTagName("td");
3. for (var i = 0; i < cells.length; i++) {
4. cells[i].style.backgroundColor = "pink";
5. }

 Here's the line-by-line breakdown.


1. Targets the table by its id
2. Assembles a collection of all the elements in the table with a td tag
3-5. Loops through all of them to change their background color

48
Objects

An object is an entity characterized by its properties and behaviours. The properties are used to
define the data members of an object while the behaviours are used to manipulate the data
members.

Consider the following table, comparing different packages offered by a webhost.

Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500

If you wanted to use this data in JavaScript, you could assign each value to a different variable,
like this.

1. var plan1Name = "Basic";


2. var plan1Price = 3.99;
3. var plan1Space = 100;
4. var plan1Data = 1000;
5. var plan1Pages = 10;
6. var plan2Name = "Professional";
7. var plan2Price = 5.99;
8. var plan2Space = 500;
9. var plan2Data = 5000;
10. var plan2Pages = 50;
11. var plan3Name = "Ultimate";
12. var plan3Price = 9.99;
13. var plan3Space = 2000;
14. var plan3Data = 20000;
15. var plan3Pages = 500;

 Having made all these variable assignments, you could then, for example, write this
JavaScript statement...
 alert("The cost of the " + plan2Name + "package is $" + plan2Price + " per
month.");
 ...and an alert would display saying, "The cost of the Professional package is
$5.99 per month."

49
 But assigning all these values to variables is unwieldy, and can lead to problems if things
get complicated.
 A better way to handle the situation is to create objects with properties.
 This is a handier scheme that more accurately reflects the 2-dimensional, gridlike nature
of the host company's table that we started with.
 This table shows all the options expressed as objects and properties.

Object plan1 plan2 plan3


name (a property) “Basic” “Professional” “Ultimate”
price (a property) 3.99 5.99 9.99
space (a property) 100 500 2000
transfer (a property) 1000 5000 20000
pages (a property) 10 50 500

 In this example, each hosting plan is an object—plan1, plan2, plan3.


 And each object has 5 properties—name, cost, space, transfer, and pages.
 Properties are just variables that are attached to an object.
 In this case, there's a string property (name) and four number properties
(price, space, transfer, and pages) for each object.
 In code we refer to objects and their properties using dot notation.
 Here's the statement that creates the alert shown above, with object-property pairs
replacing the simple variables.
 alert("The cost of the " + plan2.name + " package is $" + plan2.price + " per
month.");
 plan2.name represents "Professional".
 plan2.price represents 5.99.

 The most straightforward way to define an object and its properties is this.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10
7. };

50
Things to notice:

 The code begins like any variable definition, with the keyword var, followed by the
object name, and then an equal sign.
 But then, instead of a value, there's a curly bracket, whose twin comes at the end of the
block.
 Each property begins with a name, followed by a colon, and then a value.
 Each property definition except the last ends with a comma.
 The closing curly bracket is followed by a semicolon, because of the equal sign in the
first line.

Now let's add one more property, discountMonths.

 If the current month is July, August, or December, the customer gets a 20 percent
discount on the hosting plan.
 To keep track of those special months, we'll assign them to a new property.
 This new property is an array, not a simple variable.
 plan1.discountMonths = [6, 7, 11];
 The statement above creates a new property of the object plan1, discountMonths, and
assigns an array to it representing the three months when the customer gets a discount.
 You refer to the individual elements of this array property the same way you'd refer to the
elements of any array, with a number inside brackets, but using the dot notation of the
objectproperty pair, plan1.discountMonths.
 var mo = plan1.discountMonths[2];
 The statement above assigns the third element of the array, the number
representing December, to the variable mo.

So far, we've defined only one object, plan1, and its properties.

 To complete the set of objects that includes plan2 and plan3, you'd have to do the same
thing again, and then again.

Objects:
Properties

 To change the value of an object's number value, use a simple assignment statement, the
same way you'd assign a value to a plain variable.
 deal3.cost = 79.95;
 Whatever the value of deal3.cost was, now it's 79.95.
 You can also assign a string instead of a number.

51
 deal3.name = "Super-saver";
 Whatever the value of deal3.name was, now it's "Super-saver".
 You can also assign an array list to a property.
 deal3.features = ["Guarantee", "Free Ship"];
 Whatever the value of deal3.features was, now it's an array with the elements
"Guarantee" and "Free Ship."
 You can also assign a Boolean value.
 deal3.membersOnly = false;
 Whatever the value of deal3.membersOnly was, now it's false.

 You can also use an assignment statement to define a new property for an object.
 Suppose the object deal3 has some properties, but none of them are deal3.market.
 Now you want to add it, while assigning it a value.
 deal3.market = "regional";
 Just as you can create an undefined variable by not assigning it a value, you can create an
object without any properties.
 var deal4 = {};
 If you want to create a property now and assign it a value later, you can create it with a
value of undefined.
 deal3.market = undefined;
 Note that the keyword undefined isn't in quotation marks.
o It isn't a string.

 You can delete a property of an object.


 delete deal3.market;
 You can check to see if a property of an object exists.
 The following statement tests whether there is such a thing as deal3.market and assigns
the result (true or false) to the variable propertyExists.
 propertyExists = "market" in deal3;

Things to notice:

 You could use any legal variable name instead of propertyExists.


 The keyword in asks, "The property market is in the object deal3—true or false?"
 The property market is in quotes.
 The object deal3 is not in quotes.

52
Objects:
Methods
Consider the following chart showing different hosting plans.

Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500
Discount Mo Jul, Aug Jul, Aug, Dec Jul, Aug

 We're going to write a function that calculates the annual charge based on this chart.
 Note that if the user signs up at certain times of the year, he gets a discount for the entire
year.
 If he signs up for the Basic plan in July or August, he gets 20 per cent off.
 If he signs up for the Professional plan in July, August, or December, he gets 20 per cent
off.
 If he signs up for the Ultimate plan in July or August, he gets 20 per cent off.
 We begin by creating three objects with properties.
 This is the object and its properties that represent the Basic plan.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10,
7. discountMonths: [6, 7]
8. };

 The function below cycles through all the discount months (line 5) checking to see if any
of them happen to be the current month (line 6).
 If so, it calculates a 20 percent discount by multiplying the regular price by .8.
 Then it multiplies the monthly price, discounted or not, by 12, to get the
annual price, and returns the number to the calling code (line 11).
1. function calcAnnual() {
2. var bestPrice = plan1.price;
3. var currDate = new Date();

53
4. var thisMo = currDate.getMonth();
5. for (var i = 0; i < plan1.discountMonths.length; i++) {
6. if (plan1.discountMonths[i] === thisMo) {
7. bestPrice = plan1.price * .8;
8. break;
9. }
10. }
11. return bestPrice * 12;
12. }

 This is the calling statement that executes the function.


 var annualPrice = calcAnnual();
 Let's make the function more flexible so the discount rate can vary, depending on
the value that the calling statement passes to it.
 Here's the revision, with the percentage to be charged, passed to the parameter
percentIfDisc, if the user qualifies for a discount.
1. function calcAnnual(percentIfDisc) {
2. var bestPrice = plan1.price;
3. var currDate = new Date();
4. var thisMo = currDate.getMonth();
5. for (var i = 0; i < plan1.discountMonths.length; i++) {
6. if (plan1.discountMonths[i] === thisMo) {
7. bestPrice = plan1.price * percentIfDisc;
8. break;
9. }
10. }
11. return bestPrice * 12;
12. }

 This is the calling statement that passes the value to the function and executes it.
 In this example, it passes the value .85, representing a discount of 15 percent.
 var annual Price = calcAnnual(.85);
 As you can attach a variable to an object, and the variable becomes the object's property.
 You can also attach a function to an object, and the function becomes that object's
method.
 The method does the same task the regular function does, but now it's
attached to an object.
 The code below inserts the function coded above into the object definition, so now it's a
method.
1. var plan1 = {

54
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10,
7. discountMonths: [6, 7],
8. calcAnnual: function(percentIfDisc) {
9. var bestPrice = plan1.price;
10. var currDate = new Date();
11. var thisMo = currDate.getMonth();
12. for (var i = 0; i < plan1.discountMonths.length; i++) {
13. if (plan1.discountMonths[i] == thisMo) {
14. bestPrice = plan1.price * percentIfDisc;
15. break;
16. }
17. }
18. return bestPrice * 12;
19. }
20. };

Things to notice:

 Except for the first line, every line of the method is identical to the code used to create
the plain function that we started with.
 The method definition begins the same way a property definition begins, with the name
followed by a colon.
 A comma ends every property definition and method definition except for the last
property or method.
 If you were to add a property or method below the calcAnnual method definition, you'd
need to insert a comma after the closing curly bracket of the calcAnnual definition.
 The parentheses that indicate that a variable name is the name of a function come
immediately after the keyword function.
 Parameters, if there are any, go inside the parens, as in any function definition.
 This is how you'd call the method.
 var annualPrice = plan1.calcAnnual(.85);

 In the method definition coded above, the properties are referred to using the name of the
object—for example, plan1.price.

55
 This works, but a better approach, is to replace the name of the object with the keyword
this.
 When JavaScript sees this keyword, it knows you're referring to the object that's being
defined.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10,
7. discountMonths: [6, 7],
8. calcAnnual: function(percentIfDisc) {
9. var bestPrice = this.price;
10. var currDate = new Date();
11. var thisMo = currDate.getMonth();
12. for (var i = 0; i < this.discountMonths.length; i++) {
13. if (this.discountMonths[i] === thisMo) {
14. bestPrice = this.price * percentIfDisc;
15. break;
16. }
17. }
18. return bestPrice * 12;
19. }
20. };

 When you write this.whatever, JavaScript is smart enough to understand that you're
referring to a property of the object that's being defined—in this case, plan1.

Objects:
Constructors
Consider a version of the chart showing different hosting plans.

Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500

56
 This is how the information for the Basic plan is encapsulated in an object and five
properties.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10
7. };

 But that only gets us an object that represents the first plan.
 We would have to do the same thing again for the Professional and Ultimate plans.
 This is too much hand craftsmanship.
 In order to reduce too much work, JavaScript lets us build the objects using a constructor
function as follows:
1. function Plan(name, price, space, transfer, pages) {
2. this.name = name;
3. this.price = price;
4. this.space = space;
5. this.transfer = transfer;
6. this.pages = pages;
7. }

 This would be like a plain function definition but for two differences:
1. The function name is capitalized.
 JavaScript doesn't care whether you do this or not, but it's conventional to do it to
distinguish constructor functions from regular functions.
2. Each of the parameter values is assigned to a variable.
 But the variable is a property attached to some object whose name hasn't been
specified yet.
 Just as the parameter values will be filled in by the calling code, so will the name
of the object.
 This is the calling code that creates the object for the Basic plan.
 var plan1 = new Plan("Basic", 3.99, 100, 1000, 10);
 This would be just a regular function call if it weren't for that new.
 It's the keyword that tells JavaScript to create a new object.
 The name of the new object is plan1.
 Its properties are enumerated inside the parentheses.
57
 Now it's easy to mass-produce as many objects as you want, using the same pattern.
1. var plan1 = new Plan("Basic", 3.99, 100, 1000, 10);
2. var plan2 = new Plan("Premium", 5.99, 500, 5000, 50);
3. var plan3 = new Plan("Ultimate", 9.99, 2000, 20000, 500);

 It's common to use the same names for parameters and properties, but you don't have to.
 You could write:
1. function Plan(name, price, space, transfer, pages) {
2. this.doc = name;
3. this.grumpy = price;
4. this.sleepy = space;
5. this.bashful = transfer;
6. this.sneezy = pages;
7. }

Objects:
Constructors for methods
Consider the version of the hosting chart that includes discount months.

Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500
Discount Mo Jul, Aug Jul, Aug, Dec Jul, Aug

 When you attach a variable to an object, it's called a property of the object.
 When you attach a function to an object, it's called a method of the object.
 In the example below, the method checks to see if the current date is in a discount
month and, if so, applies the discount.
 Then the method calculates the annual charge.
 If you're creating more than one object with the same pattern of properties and methods,
 it's a convenience to build the method as well as the properties into the
constructor function.
 In the following code, the constructor creates the same method for every object that is
created, as it creates all the properties for each object.
1. function Plan(name, price, space, transfer, pages, discountMonths) {

58
2. this.name = name;
3. this.price = price;
4. this.space = space;
5. this.transfer = transfer;
6. this.pages = pages;
7. this.discountMonths = discountMonths;
8. this.calcAnnual = function(percentIfDisc) {
9. var bestPrice = this.price;
10. var currDate = new Date();
11. var thisMo = currDate.getMonth();
12. for (var i = 0; i < this.discountMonths.length; i++) {
13. if (this.discountMonths[i] === thisMo) {
14. bestPrice = this.price * percentIfDisc;
15. break;
16. }
17. }
18. return bestPrice * 12;
19. };
20. }

 Things to notice about line 8, the beginning of the method definition:


 Like the property definitions above it, the line begins with the keyword this,
referring to the name of whatever object is being constructed at any given time.
 The next three pieces are the same: a dot, the name of the method, and an equal
sign.
 The next piece is different: the keyword function.
o In this case, a single parameter is inside the parentheses, percentIfDisc.
o This is not a parameter that's part of the constructor.
o It's a parameter of the method that the constructor will create for each
object.
o A value is passed to it not when a new object is created using
the constructor, but when the method, having already been created along
with its object via the constructor, is called.
 This is the code that calls the constructor function to create three new objects that
correspond to the three hosting plans.
1. var p1 = new Plan("Basic", 3.99, 100, 1000, 10, [6, 7]);
2. var p2 = new Plan("Premium", 5.99, 500, 5000, 50, [6, 7, 11]);
3. var p3 = new Plan("Ultimate", 9.99, 2000, 20000, 500, [6, 7]);

59
 Once the objects and their properties and method are created by the code above, this is
the code that calls, for example, the method for the Premium plan.
 var annualPrice = p2.calAnnual(.85);

 The main difference between the method definition in the one-off literal object definition
(no constructor) and the method definition in the constructor function is the first line.
 In other respects, both definitions are identical.
 This is the first line of a method definition when an object is created on a one-off basis
without a constructor:
 calcAnnual: function(percentIfDisc) {
 This is the first line of a method definition within a constructor:
 this.calcAnnual = function(percentIfDisc) {
 There are two other differences.
 Because in the constructor function the method definition
begins with an assignment (something = something else), you need a semicolon
after the closing curly bracket.
 And no comma is necessary if another property or method definition follows.

Objects:
Prototypes

Consider a chart showing the three objects and their properties and method.

Hosting Plans
Object plan1 plan2 plan3
name (a property) “Basic” “Professional” “Ultimate”
price (a property) 3.99 5.99 9.99
space (a property) 100 500 2000
transfer (a property) 1000 5000 20000
pages (a property) 10 50 500
discountMonths (a property) Jul, Aug Jul, Aug, Dec Jul, Aug
calcAnnual (a method) Calculates Calculates Calculates
annual charge annual charge annual charge

60
 Each object corresponded to a hosting plan.
 Each object had six properties and one method.
 The properties shown in the rows above are customized for each object, but the method is
always the same from object to object.
 The constructor function keeps duplicating the same method for each object, object
after object.
 If we were to create 100 objects using the constructor, JavaScript would duplicate the
same method 100 times, once for each object.
 It would work, but it is not pretty.
 The table below, which shows all of the objects sharing a single method, makes more
sense.

Object plan1 plan2 plan3


name (a property) “Basic” “Professional” “Ultimate”
price (a property) 3.99 5.99 9.99
space (a property) 100 500 2000
transfer (a property) 1000 5000 20000
pages (a property) 10 50 500
discountMonths (a property) Jul, Aug Jul, Aug, Dec Jul, Aug
calcAnnual (a method) Calculates annual charge(Shared by all objects)

 We want only one copy of the method, shared by all objects created with the constructor,
no matter how many objects are created.
 This achieved with the use of a prototype statement.
 First, we don't include the method in the constructor function, because that creates a copy
of the method for every single object that's created with the constructor.
 Instead, we define the method as a prototype of the constructor as follows:
1. Plan.prototype.calcAnnual = function(percentIfDisc) {
2. var bestPrice = this.price;
3. var currDate = new Date();
4. var thisMo = currDate.getMonth();
5. for (var i = 0; i < this.discountMonths.length; i++) {
6. if (this.discountMonths[i] === thisMo) {
7. bestPrice = this.price * percentIfDisc;
8. break;
9. }
10. }

61
11. return bestPrice * 12;
12. };

 Now, all objects created with the constructor Plan will share the same copy of the
method calcAnnual.
 There's no unnecessary duplication.
 Note that except for the first line, the method is coded exactly as when it was
part of the constructor definition.
 Even the first line is the same, if you consider only the parts on the right side of the equal
sign.
 The parts on the left side, connected by dots, are:
 the name of the constructor function, in this case Plan the keyword prototype
the name of the method that all objects created with Plan will share, in this case
calcAnnual

 Objects can have prototype properties as well as prototype methods.


 Suppose you wanted all objects created with the Plan to share the same property,
cancellable, with a value of true.
 You'd code the prototype this way:
 Plan.prototype.cancellable = true;
 Now all objects created with the constructor function Plan share a property,
cancellable, whose value is true.

This is how the object table looks with the prototype method and the prototype property.

Object plan1 plan2 plan3


name (a property) “Basic” “Professional” “Ultimate”
price (a property) 3.99 5.99 9.99
space (a property) 100 500 2000
transfer (a property) 1000 5000 20000
pages (a property) 10 50 500
discountMonths (a property) Jul, Aug Jul, Aug, Dec Jul, Aug
calcAnnual (a method) Calculates annual charge(Shared by all objects)
Cancellable(a property) True (Shared by all objects)

 It's possible to override a prototype for any individual object.


 For example, suppose you want all objects created with the constructor to share the same
cancellable property, except for the least expensive plan, plan1, with the name "Basic."

62
 You achieve this by using the statement:
 plan1.cancellable = false;
 All objects created with the constructor still share the property cancellable, but now
the value of that property for one object is different from all the others.

Here's the chart that shows.

Object plan1 plan2 plan3


name (a property) “Basic” “Professional” “Ultimate”
price (a property) 3.99 5.99 9.99
space (a property) 100 500 2000
transfer (a property) 1000 5000 20000
pages (a property) 10 50 500
discountMonths (a property) Jul, Aug Jul, Aug, Dec Jul, Aug
calcAnnual (a method) Calculates annual charge(Shared by all objects)
Cancellable(a property) Exception: this one’s true
false (Shared by all objects)

Objects:
Checking for properties and methods

 You can check to see if an object has a particular property by writing a simple statement
like this:
 var gotTheProperty = "price" in plan1;
 Here are the parts:
 the property in question, enclosed in quotes—in this case, price the keyword in
the object, in this case, plan1
 Again, the question is, does the object named plan1 have a property called price?
 In other words, is there such a thing as plan1.price?
 In the example of three hosting plans that we've been using, plan1 does have a price,
3.99.
 So gotTheProperty is assigned true.
 But plan1 doesn't have a property named location.
 So if we write...
 var gotTheProperty = "location" in plan1;
 ...the variable gotTheProperty is false.
 plan1 in the example also has a method named calcAnnual.
 A method is a type of property of an object, so if you write...

63
 var gotTheProperty = "calcAnnual" in plan1;
 ...the variable gotTheProperty is true.

 Things to notice:
 The property, a variable, is enclosed in quotation marks.
 We're not used to putting JavaScript variables inside quotation marks, so this is
something to make a note of.
 The keyword is in—pretty intuitive.
o The code asks, "Is there a property called 'price' in plan1?"
 If you want a list of an object's properties, you use the following code:
1. var listOfProperties = [];
2. for (var prop in plan1) {
3. listOfProperties.push(prop);
4. }

 Line 1 declares an empty array, listOfProperties.


 Lines 2-4 cycle through all the properties of plan1, adding each property (push),
including any methods, to the array listOfProperties.
 Using the example we've been working with, the array listOfProperties winds up with a
value of "name,price,space,transfer,pages,discountMonths,calcAnnual".
 Note that, unlike a regular for loop, this one doesn't establish a limit on the number of
loops or increment a counter.
 After each iteration, JavaScript automatically moves to the next property of the object
and stops iterating when there are no more properties to enumerate.
 Note also that instead of prop, you could use any other legal variable name.
 In the example, the method, calcAnnual, wasn't included in the original definition of the
object plan1.
 It was later added to the prototype of the constructor function that was used to
create the object, and so became a property of the object by inheritance.
 The code above includes inherited properties (including methods) in the collection.
 If you want to limit the list of properties to those that have been explicitly declared for
the object, omitting those that are inherited from a prototype, you need to use
hasOwnProperty.
1. var listOfProperties = [];
2. for (var prop in plan1) {
3. if (plan1.hasOwnProperty(prop)) {
4. listOfProperties.push(prop);
5. }
6. }
64
 In the example above, each property in turn is assigned to the variable prop.
 Then the if statement tests to see if it's a property owned by the object as opposed to
being inherited through a prototype.
 You can test a literal property name instead of using a variable.
 var isOwnedProperty = plan1.hasOwnProperty("price");

Browser control:
Getting and setting the URL

 In addition to making things happen on the webpage, you can use JavaScript to control
the browser.
 You can get the browser to tell you its current location using the statement:
 var whereWeAt = window.location.href;
 For example, if the browser is currently at
http://www.mybeautifulsite.com/products/page33.html#humidifier,
 the statement above will assign the string
"http://www.mybeautifulsite.com/products/page33.html#humidifier"
to the variable whereWeAt.
 You can also get pieces of this.
 This statement gets just the domain name.
 var theDomain = window.location.hostname;
 In the example, the string "www.mybeautifulwebsite.com" is assigned to the variable
theDomain.
 "http://", the path, and the anchor are omitted.
 You get the path as follows:
 var thePath = window.location.pathname;
 In the example, the string "/products/page33.html" is assigned to the variable thePath.
 If the browser were on the home page and the URL were simply
http://www.mybeautifulsite.com, the string "/" would be assigned to the variable.
 In the example, the browser has been pointed to a section of the page marked by the
anchor #humidifier.
 This statement identifies the anchor.
 var theAnchor = window.location.hash;
 The string "#humidifier" is assigned to the variable theAnchor.
 If there is no anchor in the URL, the variable is assigned an empty string, "".
 As usual, you can reverse the order of things, telling the browser where to go instead of
asking where it is using the statement:

65
 window.location.href = "http://www.me.com/1.html";
 The statement above tells the browser to navigate to the page named 1.html at the site
me.com.
 If you wanted the browser to navigate to the site's home page, you'd write...
 window.location.href = "http://www.me.com";
 And if you wanted it to land on an anchor...
 window.location.href = "http://www.me.com/1.html#section9";
 It would be nice if you could use window.pathname = ... to move to a different page
on the current site or window.hash = ... to move to an anchor on the current page, but you
can't.
 What you can do, though, is query the browser for the domain name and combine that
with the page where you want to go using the following code:
1. var currentSite = window.location.hostname;
2. var destination = "http://" + currentSite + "/wow.html";
3. window.location.href = destination;

Here's the line-by-line breakdown:

1. Gets the domain name and assigns it to the variable currentSite.


 Example: www.me.com
2. Concatenates the string "http://" with the domain name plus the destination page and
assigns the combo to the variable destination
3. Directs the browser to the destination

This is how to direct the browser to an anchor on the current page.

1. var currentSite = window.location.hostname;


2. var currentPath = window.location.pathname;
3. var destination = "http://" + currentSite + currentPath + "#humidifier";
4. window.location.href = destination;

Here's the breakdown:

1. Gets the domain name and assigns it to the variable currentSite.


Example: www.me.com
2. Gets the pathname and assigns it to the variable currentPath.
Example: /1.html
3. Concatenates the string "http://" with the domain name, the destination page, and the
desired anchor and assigns the combo to the variable destination
4. Directs the browser to the destination

66
Coding alternatives to be aware of:

 You can omit window.


 It's legal to use location.href, location.hostname, location.pathname, and
location.hash.
 It's more common to include window.
 You can omit href when you're detecting the URL.
 It's legal to use window.location, or simply location.
 Including href is preferred for esoteric reasons.
 You can use document.URL as an alternative to window.location.href

Browser control:
Getting and setting the URL another way

 You can direct the browser to a new URL by using the following statement
 window.location.assign("http://www.me.com");
 The statement directs the browser to the home page of me.com.
 As with the window.location.href statement, you can make the URL as detailed as you
like.
 window.location.assign("http://www.me.com/lojack.html#guarantee");
 The statement directs the browser to the anchor #guarantee on the lojack.html
page of the site me.com.
 Here's another alternative that has a slightly different effect.
 window.location.replace("http://www.me.com/lojack.html#guarantee");
 Once again, the statement directs the browser to a new URL.
 But by using replace instead of assign, you interfere with the browser history.
 When you use assign, the history is intact.
 The statement takes the user away from the original page, to the new page.
 If, after arriving at the new page, she presses the Backspace key or clicks the
browser's back button, she goes back to the original page that she just came from.
 But when you use replace, the original page doesn't make it into the history.
 If the user presses Backspace after being taken to the new page, she's taken to the
page that displayed before the original page since the original page is no longer in
the history.
 If there is no page before the original page, nothing happens when she presses
Backspace.
 To reload the current page code one of these statements:
 window.location.reload(true);
 window.location.reload(false);
 window.location.reload();

67
 All three statements reload the current page.
 If the argument is true (example 1 above), the statement forces the browser to
load the page from the server.
 If the argument is false (example 2) or if there is no argument (example 3), the
browser will load the page from the cache if the page has been cached.

Coding alternatives to aware of:

 You can use window.location.href = window.location.href or any of the


abbreviated alternatives to reload the current page.
 The reload is faster, but it doesn't allow you to specify whether the browser reloads from
the server or the cache.

Browser control:
Forward and reverse

 You can make the browser go back one URL in the browser history, as if the user has
pressed the Backspace key or clicked the browser's back button.
 Use the statement: history.back();
 To make the browser go forward in the history, as if the user has pressed alt-right-arrow
or clicked the browser's forward button...
 Use the statement: history.forward();
 In both cases, if there is no URL in the history that would make the move possible, the
browser does nothing.
 You can tell the browser how many steps in the history you want to take, using negative
numbers to go back and positive numbers to go forward.
 The following statement is the equivalent of pressing the Backspace key three times.
 history.go(-3);
 The following statement sends the browser forward two URLs.
 history.go(2);
 If a negative number inside the parentheses is greater than the number of previous URLs
in the history, the browser will do nothing.
 If a positive number inside the parentheses is greater than the number of forward URLs in
the history, the browser will do nothing.
 When you want to go forward or backward just one step, you can choose either method..
 history.back(); or
 history.go(-1);
And...
 history.forward(); or
 history.go(1);

68
 There is no reliable way to find out how many items, backward and forward, there are in
the history.
 If the user clicked a link to get to the current page, you can get the URL of the page
where the link was clicked.
 var whereUserCameFrom = document.referrer;
 The statement above assigns the URL where the link was clicked to the variable
whereUserCameFrom.
 However, this works only if a link was clicked, including a link in a search result.
 If the user got to your page through a bookmark or by entering your URL in the
address bar, the result of document.referrer will be an empty string, "".

Browser control:

Filling the window with content

 A window can be created using the basic statement:


 var monkeyWindow = window.open();
 The code above opens a blank window of maximum size and gives it a handle, a variable
that refers to this particular window—in this case, monkeyWindow.
 Depending on the browser, the window may open on top of the previous window, in a
new tab, or even in a new copy of the browser.
 You can't control this.

There are three ways to fill a new window with content

a) You can use the write method to put HTML content on the screen
1. var monkeyWindow = window.open();
2. var windowContent = "<h1>Capuchin monkey</h1><img src= 'monkey.jpg'><p>The
word capuchin derives from a
group of friars<br>named the Order of Friars Minor Capuchin who wear<br>brown
robes with large hoods covering their heads.</p>";
3. monkeyWindow.document.write(windowContent);

Here's the line-by-line breakdown:

1. Opens a new window and assigns it the handle monkeyWindow


2. Assigns text to the variable windowContent
3. Fills the window with the text

69
Things to notice:

 Inside the main quotes that enclose the whole string, any quoted text must be in single
quotes, as in <img src='monkey.jpg'>.
 Using the document.write method, you place the HTML string on the page.
 You designate the window by its handle, the variable that you declared when you opened
the window.
 The document.write method in this example is used to fill an empty window with content.
 You could also use it to write to a window that already has content.
 But it will overwrite all the HTML of the original document, replacing its content
entirely.
 Instead of assigning the HTML string to a variable and specifying the variable inside the
parentheses, you could just put the HTML string inside the parentheses, enclosed in
quotes of course.
 But this would be even more unwieldy than the example code.

b) The second way to fill the window with content is to assign a document to it
 monkeyWindow.location.assign("http://www.animals.com/capuchin.html");
...or...
 monkeyWindow.location.href = "http://www.animals.com/capuchin.html";

c) The third and most common way to fill the window with content is to include the
document assignment in the statement that opens the window.
 var monkeyWindow = window.open("http://www.animals.com/capuchin.html");
 If the document you're opening in the popup shares the same host and directory as the
original document, you can just write...
 var monkeyWindow = window.open("capuchin.html");
 This is how you close a window.
 monkeyWindow.close();

Browser control:
Controlling the window's size and location

 You can open a window with two parameters.


 The first parameter is URL
 The second parameter a window name.
 The code is:
 var monkeyWindow = window.open("monk.html", "win1");
 In the statement above, the second item in the parentheses, "win1", is the name.

70
 The name is useful for specifying the target attribute of an <a> or <form> element in
HTML.

Things to know:

 The name, used in HTML, is not the handle.


 The handle is used in JavaScript statements that write to the window, assign a URL to it,
or close it.
 The handle is the variable that precedes the equal sign.
 The name is in quotes.
 The name is separated from the URL by a comma followed by a space.
 The name itself can't have spaces in it.
 You can specify a URL parameter without a name parameter, but you can't specify a
name parameter without a URL parameter.
 But it is okay to specify an empty URL parameter, like this.
 var monkeyWindow = window.open("", "win1");

Often, you'll want to specify a window size.

 var monkeyWindow = window.open("monk.html", "win1", "width=420,height=380");

Things to know:

 Both parameters, width and height, are enclosed by a single set of quotation marks.
 The absence of spaces within the quotation marks isn't a mere style preference but a
requirement.
 Any spaces here will break JavaScript.
 The numbers refer to pixels.
 In the example above, the window will be 420 pixels wide and 380 pixels high.
 Width and height must be a minimum of 100.
 Unlike the URL and name parameters, the order doesn't matter.
 Width can come before height, height can come before width.
 But the width-and-height set must come third, after URL and name.
 In order to specify these parameters, you must specify a URL and name, even if
you specify empty strings.
 A window that's smaller than the screen will display in the upper-left corner of the
screen.
 But you can optionally tell the browser where to place the window.
var w = window.open("", "", "width=420,height=380,left=200,top=100");

71
Things to know:

 The numbers are pixels—number of pixels from the left edge of the screen and
number of pixels from the top of the screen.
 The positioning parameters are included within the same set of quotation marks as the
size parameters, and, like the size parameters, are separated by a comma and no space.
 The parameter order within the quotation marks doesn't matter.
 You can specify window size without specifying window position,
 but if you specify window position without size,
 it will be ignored since it will be a full-size window that fills the whole screen.
 Some or all of the parameters can be assigned to a variable, and the variable
can be used in the statement that opens the window.
 Since the whole thing has to be a quoted string, the quotes within the string have to be
changed to single quotes.
1. var windowSpecs = "'faq.html', 'faq', 'width=420,height=380,left=200,top=100'";
2. var faqPage = window.open(windowSpecs);

Browser control:
Testing for popup blockers

 Popup blockers are now a standard feature of browsers, with some level of popup
blocking usually built in as a default.
 JavaScript popups, and especially those that open a new page within the same website,
are often tolerated by default, but you can never be sure.
 If popups are an essential feature of your site, you need to test whether your popups are
going to be blocked.
 If they are, you can ask the user to disable the popup blocker for your site.
 The test is pretty inelegant.
 You attempt to open a small test popup, then quickly close it - so fast that the user may
not notice the little screen flash.
 If the attempt succeeds, the window's handle will have a value.
 If the popup is blocked, the handle will be null, and you can deliver your message to the
user.
 Here's the code.
1. function checkForPopBlocker() {
2. var testPop = window.open("", "","width=100,height=100");
3. if (testPop === null) {
4. alert("Please disable your popup blocker.");
5. }

72
6. testPop.close();
7. }

Here's the line-by-line breakdown:

2. Attempts to open a tiny window


3-4 If the handle is assigned null, meaning the window couldn't open, an alert displays
6 Closes the window

The function shown above works with all browsers except Internet Explorer.

 In Internet Explorer, if the popup is blocked, the handle will be undefined instead of null.
So to cover all bases, you need to code the function this way.
1. function checkForPopBlocker() {
2. var testPop = window.open("", "","width=100,height=100");
3. if (testPop === null || typeof(testPop === "undefined") {
4. alert("Please disable your popup blocker.");
5. }
6. testPop.close();
7. }

Normally, you'd run the test when the page loads.

 <body onLoad ="checkForPopBlocker();">

Form validation: text fields

 JavaScript helps you find out if the user is filling out your forms correctly
 that is, helps you validate your form.
 With form validation, if there's a problem, you can ask the user to try
again.
 To begin with, if you have a required field, you can check to see if the user has entered
something in it.
 Let's start with a simple form that asks the user to enter her last name.
 Here's some markup for the form:
<form onSubmit="return checkForLastName();">
Please enter your last name.<br>

73
<input type="text" id="lastNameField">
<input type="submit" value="Submit Form">
</form>

 When the user clicks the Submit button, the function checkForLastName is called.
 Here's the function.
1. function checkForLastName() {
2. if (document.getElementById("lastNameField").value.length == 0) {
3. alert("Please enter your last name");
4. return false;
5. }
6. }

 Line 2 asks whether the length of the value found in the field with the id "lastNameField"
is 0.
 That is, is nothing entered there?
 If so, an alert displays asking the user to enter her name.
 And then in line 4 something else happens.
 The Boolean value false is returned to the calling code.
 This prevents the form from being submitted.
 In order for the submission to be called off, there has to be a matching keyword return in
the markup that calls the function.
 Without this return in the calling code, the return in line 4 of the function won't
stop the form from being submitted.
 <form onSubmit="return checkForLastName();">

 As a user-friendly touch, you can use the focus method to place the cursor in the field
that needs to be completed.
1. function checkForLastName() {
2. if (document.getElementById("lastNameField").value.length === 0) {
3. alert("Please enter your last name");
4. document.getElementById("lastNameField").focus();
5. return false;
6. }
7. }

Repeating the document.getElementId... designation gets pretty unwieldy, so let's put


it into a variable.

74
1 function checkForLastName() {
2 var targetField = document.getElementById("lastNameField");
3 if (targetField.value.length === 0) {
4 alert("Please enter your last name");
5 targetField.focus();
6 return false;
7}
8}

 Let's add one more feature.


 We'll direct the user's attention to the field that needs to be completed by giving it a
yellow background color.
 This requires two additional statements.
 If the user hasn't completed the field, line 6 changes its background color to
yellow.
 After the user completes the field, line 9 restores the background color to white
when the function runs again on the user's subsequent submission.
1. function checkForLastName() {
2. var targetField = document.getElementById("lastNameField");
3. if (targetField.value.length === 0) {
4. alert("Please enter your last name");
5. targetField.focus();
6. targetField.style.background = "yellow";
7. return false;
8. }
9. targetField.style.background = "white";
10. }

Coding alternative to be aware of:

 The sample code in this chapter targets forms and fields by ID, which is the most
straightforward approach.
 But you could target by name, by tag, or by position in the DOM hierarchy.
 Instead of hard-wiring the ID into the function, you could potentially make it multi-use
by naming the field ID as a parameter, and passing the ID to it from the calling code.

75
Form validation: drop-downs

 Consider a form with a select-a-state field.


 Let us limit the list of states to just 4, for simplicity.
 When the user clicks the up or down arrow to the right of SELECT A STATE,
 a menu drops down.
 She selects a state from it.
 But what happens if she forgets to select a state?
 Here's the markup, simplified for teaching purposes.
<form onSubmit="return checkForSelection();">
<select id="states">
<option value="" selected="selected">
SELECT A STATE</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
</select>
<input type="submit" value="Submit Form">
</form>

 When the Submit button is clicked, the function checkForSelection is called.


 Note that once again, the keyword return precedes the function call.
 Here's the function.
1. function checkForSelection() {
2. if (document.getElementById("states").selectedIndex == 0) {
3. alert("Please select a state.");
4. return false;
5. }
6. }

 In the function, if selectedIndex is 0 (line 2), it means the user hasn't made a selection.
 Line 3 displays an alert asking her to select.
 Line 4 returns false, cancelling the form submission.

76
Here's the function, revised two ways.

 First, it accepts the element ID as a parameter, allowing it to process more than one form.
 Second, the element is assigned to a variable.
1. function checkForSelection(selecID) {
2. var target = document.getElementById(selecID);
3. if (target.selectedIndex === 0) {
4. alert("Please select a state.");
5. return false;
6. }
7. }

 The function coded above needs the event-handler to include the ID as an argument.
 <form onSubmit="return checkForSelection('states');">

Form validation: radio buttons

 Let's code a form with a group of radio buttons.


 The buttons are Cat, Bat, and Hat.
 This is the markup, simplified to keep your focus on what you're learning here.
<form onSubmit="return validateRadios();">
<input type="radio" name="r1" value="cat"> Cat<br>
<input type="radio" name="r1" value="bat"> Bat<br>
<input type="radio" name="r1" value="hat"> Hat<br>
<input type="submit" value="Submit Form">
</form>

 Note that the radio buttons all have the same name, "r1".
 This is the validating function that checks to see if the user has clicked one of the buttons.
1. function validateRadios() {
2. var radios = document.getElementsByName("r1");
3. for (var i = 0; i < radios.length; i++) {
4. if (radios[i].checked) {
5. return true;
6. }
7. }
8. alert("Please check one.");
9. return false;
10. }

77
 Line 2 makes a collection of all the buttons with the name "r2" and assigns the collection
to the variable radios.
 This is possible because, though an element can't share its id with any
other elements, any number of elements can share the same name.
 Lines 3 and 7 loop through collection to see whether any of the buttons is checked.
 If so, the code breaks out of the function with the return keyword in line 5,
passing back the Boolean true so the form can be submitted.
 If the loop runs its course without finding any buttons checked, line 8 displays an
alert and line 9 returns false, cancelling the form submission.
 The function can be used to validate button sections for any number of forms if we
specify a parameter, allowing the event-handler to pass the button group name to the
function.
1. function validateRadios(ename) {
2. var radios = document.getElementsByName(eName);

 In order to use the function coded above, the event-handler would have to include the
button group name as an argument.
 <form onSubmit="return validateRadios('r1');">

Form validation: ZIP codes

 Let us consider a one-field form that asks the user to enter her ZIP code.
 You need to test whether she's entered the right number of digits for a ZIP - n5 digits.
 HTML gives you a way to keep her from entering too many digits: maxlength = 5.
 But if you want to make sure she hasn't entered too few digits, you need to use
JavaScript.
 Here's the function.
1. function validateZIP() {
2. var numChars = document.getElementById("zip").value.length;
3. if (numChars < 5) {
4. alert("Please enter a 5-digit code.");
5. return false;
6. }
7. }
 If the number of characters in the field is fewer than 5, an alert displays and false is
returned to the calling code, cancelling the form submission.
 Another question to ask about the ZIP field entry is whether the user has entered only
numbers.

78
 Here's the additional code for that.
1. function validateZIP() {
2. var valueEntered = document.getElementById("zip").value;
3. var numChars = valueEntered.length;
4. if (numChars < 5) {
5. alert("Please enter a 5-digit code.");
6. return false;
7. }
8. for (var i = 0; i <= 4; i++) {
9. var thisChar = parseInt(valueEntered[i]);
10. if (isNaN(thisChar)) {
11. alert("Please enter only numbers.");
12. return false;
13. }
14. }
15. }

 The highlighted code loops through the five characters that have been entered, checking
to make sure that all the characters are string characters representing numbers.
 Because the five characters in the field are string characters, each one has to be converted
to a number if possible before being tested.
 Line 9 does this.
 Line 10 tests to see whether the attempted conversion worked.
 If a number resulted from parseInt in line 9, no problem.
 But if the character isn't a number after the conversion attempt - if it isNaN in line
10 - an alert displays and false is returned, cancelling the form submission.

Form validation: email

 Validating an email field includes checking to make sure there are no illegal characters,
like spaces, and that all the essentials of a legal email address are there: one or more
characters, followed by @, followed by one or more characters, followed by a dot,
followed by two to four characters.
 The standard way to test for all this is to match the user's entry with
a regular expression.
 Meanwhile, here's how to head off many user errors by using indexOf.
 Let's start by checking for spaces, which are illegal in an email address.

79
1. function validateEmail() {
2. var eEntered = document.getElementById("email").value;
3. if (eEntered.indexOf(" ") !== -1) {
4. alert("No spaces allowed in address");
5. return false;
6. }
7. }

 Line 3 is the key here.


 If the index of the illegal space character is anything other than -1,
 it means the character is in there somewhere, and an alert displays.
 If you wanted to, you could test for the presence of all the other illegal characters the
same way.
 But in that case, you'd be better off using a regular expression.
 In an email address you want to see the @ sign at least one character from the beginning
of the string and no closer to the end of the string than 5 characters away.
 Here's a line that adds this test to the example function.
1. function validateEmail() {
2. var addressIsLegal = true;
3. var eEntered = document.getElementById("address").value;
4. if (eEntered.indexOf(" ") !== -1) {
5. addressIsLegal = false;
6. }
7. if (eEntered.indexOf("@") < 1 || eEntered.indexOf("@") > eEntered.length - 5) {
8. addressIsLegal = false;
9. }
10. if (addressIsLegal === false) {
11. alert("Please correct email address");
12. return false;
13. }
14. }

80
About line 7:

 The first part, left of the pipes, tests whether the character is at the beginning of the
address, which would be illegal.
 The second part, right of the pipes, tests whether there are fewer than 4 characters
following the character.
 Since there must be at least one character for the domain name plus a dot plus at least two
characters for the extension, fewer than 4 characters following the @ would be illegal.
 Finally, we will add a test for the dot that needs to be at least 1 character away from the
"@" and have 2 to 4 characters following it.
1. function validateEmail() {
2. var addressIsLegal = true;
3. var eEntered = document.getElementById("address").value;
4. if (eEntered.indexOf(" ") !== -1) {
5. addressIsLegal = false;
6. }
7. if (eEntered.indexOf("@") < 1 || eEntered.indexOf("@") > eEntered.length - 5) {>
8. addressIsLegal = false;
9. }
10. if (eEntered.indexOf(".") - eEntered.indexOf("@") < 2 || eEntered.indexOf(".") >
eEntered.length - 3) {
11. addressIsLegal = false;
12. }
13. if (addressIsLegal === false) {
14. alert("Please correct email address");
15. return false;
16. }
17. }

Line 10:

 There must be at least one character between the dot and the @.
 The first part, left of the pipes, tests whether that one character (or more) is missing,
which would be illegal.
 There must also be at least 2 characters following the dot.
 The second part, right of the pipes, tests whether there are fewer than 2 characters
following the character, which would be illegal.

81

You might also like