0% found this document useful (0 votes)
36 views132 pages

JavaScript - For Beginners - Francis John Thottungal

This document provides an overview of JavaScript and covers topics such as variables, operators, conditions, loops, functions, events, objects, and more. It is intended to teach JavaScript from the ground up. The document contains examples and explanations of JavaScript concepts.

Uploaded by

duyanh011286
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views132 pages

JavaScript - For Beginners - Francis John Thottungal

This document provides an overview of JavaScript and covers topics such as variables, operators, conditions, loops, functions, events, objects, and more. It is intended to teach JavaScript from the ground up. The document contains examples and explanations of JavaScript concepts.

Uploaded by

duyanh011286
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

Table of Contents

1 Overview
2 First Program
3 Variables
4 Operators
5 Conditions
6 Loops
7 Functions
8 Events
9 Objects
10 Number
11 Boolean
12 Strings
13 Arrays
14 Date
15 Actions in Math
16 Regular Expressions
17 Refresh and Redirect
18 Cookies
19 DHTML
20 Browser Windows
21 Moving Objects
22 Appendix I- Creating a simple drop down menu
Overview
JavaScript is a language for the world wide web. All websites use hyper text
markup language(html) as the base for making a website. There are pages that
are written in more advanced languages such as ASP, PHP, Python etc but the
base still remains html. The hypertext markup language had limitations and
these limitations are addressed by several languages including JavaScript.

Languages such as ASP, PHP, Python etc allow a website to interact with
servers and external files when needed. They bring in a dynamism with
relation to the server and external objects. Thus when a form is required to be
filled and its details have to be saved these languages come into play.

JavaScript on the other hand like html is a client side language that makes the
web pages lively. Floating surveys, greetings, interactive forms which has
certain life to it, light weight games etc are some of its functions on the
website.

It is possible to have a website without JavaScript. However, when it comes


interactivity, friendliness, dynamism neither html nor some of the languages
mentioned can beat JavaScript.

The basic requirement for understanding or using JavaScript is some


background in html or hypertext markup language.

The following points are the advantages of JavaScript:

Less server interaction: JavaScript can be used validate user input before
sending the page off to the server.
Immediate feedback to the visitors: JavaScript can help users of a webpage
with info immediately without server connection.
Increased interactivity: Messages and dynamism can be added when mouse
moves over parts and objects of a webpage.
Richer interfaces: Drop down menus etc can help the user to have a rich
experience at the webpage.
JavaScript is an interpreted language which is lightweight and makes an
otherwise static page made through html into something dynamic.
Before we start:

JavaScript can be run on all standard browsers in the market as long as it is


enabled in the browser being used.

So find the browser that is on the computer and see the following:

Internet Explorer

Follow Tools -> Internet Options from the menu.


Select Security tab from the dialog box.
Click the Custom Level button.
Scroll down till you find the Scripting option.
Select Enable radio button under Active scripting.
Finally click OK and come out.

Firefox

Open a new tab -> type about: config in the address bar.
Find the warning dialog. Select I’ll be careful, I promise!
Find the list of configure options in the browser.
In the search bar, type JavaScript. Enabled.
Find the option to enable or disable JavaScript by right-clicking on the value
of that option -> select toggle.

Google Chrome

Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
Show advanced settings at the end of the page.
Under Privacy section, click the Content settings button.
In the "JavaScript" section, select "Do not allow any site to run JavaScript" or
"Allow all sites to run JavaScript (recommended)".

For other browsers please check their respective help sections.

The tools needed to JavaScript is the program notepad or similar editor and a
browser. Initially an internet connection may not be required but having a
connection on the computer can greatly help in more advanced programming
that one will make down the line.

The JavaScript will be part of the html website. It could be encapsulated into
pages where there is a mix of html and other languages. However, the
examples in this book will be largely with html code.

Coding is best understood or appreciated when typed or written, therefore


when learning JavaScript from this book write the code in to your favorite
editor and check their working.

Many standard software packages such as Dreamweaver or Frontpage or


Homesite among others are available for writing JavaScript but there is really
no need for all these and when learning a language, the first time it is best to do
it from scratch.

Few other aspects of JavaScript are:

1. It is case sensitive.

2. Semicolons are optional after statements. However, most programmers are


used to putting this so do expect it in the examples in this book.

3. JavaScript ignores spaces, tabs, and newlines that appear in the programs.
Therefore, spaces, tabs, and newlines can be used freely in a program to make
it presentable and readable.
4. Any text between a // and the end of a line is treated as a comment. Any text
between the characters /* and */ is used for large comments. JavaScript also
recognizes <! --. as a single-line comment, just as it does the // comment. The
closing comment should be written as //-->.

This book will use the C style approach of // for single comments and /* */ for
larger comments.
Chapter 1. First Program

It is traditional in computer science classes or subjects related to programming


to write a first program that prints the words "Hello World".

Thus with that in mind this is how it is done.

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

So in notepad or similar editor save this code with the extension .html. In this
case hello.html. Observe the file with Explorer/Chrome/Firefox. How to do
that? First save file as hello.html say on the desktop or any folder on your
computer. Point the mouse to the file and right click. Choose open with and
choose the browser of your choice. Test the code on as many browsers as is
available on the computer.

In explorer sometimes a message comes up saying allow this script to run or


block. Say yes allow it to run. Check the browser settings as described in the
overview. The above code shows hello world in the left hand corner of the
browser window and if JavaScript is not available in your browser the
message "Sorry.... JavaScript is needed" will be displayed. Notice the location
where the <script language=> and </script> is located. After body declaration
in this case.

In the code above and in all JavaScript codes the <script language=> </script>
is required. It tells the browser that what is in between these tags are related to
JavaScript. The placement of the script tags can be in any four places as
follows:

1. Between <head> and </head> and hence before <body>

2. Between <body> and </body> as in the case above.

3. Between <head> and </head> and also between <body> and </body>. In
this case generally a declaration of JavaScript function etc. is made in the
head section and referenced in the body location where it is needed.

4. The script is in an external file and then included in the <head></head>


section.

If the JavaScript code is in case two above, then as the web page loads the
contents or action written within the code will run automatically. If the code is
shared on many pages then it is possible to create a text file with extension
“.js” that contains the JavaScript code. In this case the script tag will look like
this:

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

Filename can be any name that makes sense with respect to the website being
developed. To prevent browsers from showing the code if they do not support
JavaScript for any reason one could use the following format when writing
code in JavaScript.

<body>
<script language=”JavaScript”>
<!--
document.write(“Hello”);
// -->
</script>
</body

The tags <!-- and corresponding //--> will make sure that no code is shown if
JavaScripting is not available on the browser being used. A way to check to if
JavaScript is as follows: The response is either true or false.

<html>
<body>
<script language="JavaScript">
<!--
var haveJava = navigator.javaEnabled();
document.write("Java is enabled: " + haveJava);
// -->
</script></body></html>
Chapter 2. Variables
Variables exist in all programming languages. They hold temporarily various
types of data and perform actions on them as required by the programmer.

JavaScript supports three primitive data types:

Number, String and Boolean.

It also supports objects and two trivial data types null and undefined. Note that
JavaScript is case sensitive. JavaScript stores numbers in the floating point
representation.

So let us look at this code:

<html>
<body>
<script language="javascript" type="text/javascript">
var book = "Javascript-made easy";
document.write(book);
</script>
</body>
</html>

Notice here the placement of the <script> tags are in the body of the html page.
The variable was defined and the value of the variable was asked to be written
in the body of the html page.

Similarly, one could define variables for numbers. The difference is that for
numbers there is no quotation marks like for the string shown above. Unlike
other programming languages there is no need to mention if a number is an
integer, or a float or a double because JavaScript uses a float representation
for all numbers.

There are two types of variables in every programming language-global and


local. Some languages may have more categories. Global variables are
accessible by all functions but local variables defined within a function have
meaning only within that function.

Names of variables have to be unique and have some relevant meaning with
respect to the program being created. If local variable name and global
variable name is the same then within the function the local variable name will
take precedence over the global variable name.

Like any programming language JavaScript has some reserved words that
cannot be used as variable names. In addition to these reserved words the
following

Names should not start with a numeral (0-9). Names must begin with a letter or
an underscore character. JavaScript is case sensitive therefore x and X are two
different variable names.

Following is a list of reserved words in JavaScript. This is not an exhaustive


list.

double export new


abstract extends null
break false short
byte final super
case float switch
catch for this
char function throw
const goto throws
continue If transient
debugger implements true
default import try
delete in var
do int void
else interface while
if long with
enum native void
It is best to follow the rules of naming in any language and choose a name for
the variable based on what that variable holds or should hold or do. This will
help to make the program more readable and understandable.

A program once written might look foreign after many months or years if one
has to update or it and having an understandable program will greatly help in
such an event.
Chapter 3. Operators
Operators act on variables and constants and exist in every programming
language and in math.

The most common of the operators in JavaScript are:

Assignment operators (=) :

x = 2; This operation takes place from right to left. So here, x=2.


y = z; The statement assigns the value contained in z to the variable y. The
value currently in y is lost and replaced with value of z. If z changes at a later
moment, it will not affect the new value taken by y.

Arithmetic Operators (+, - , * , / , % , ++, --) :

The five arithmetical operators that are common to almost all languages and
something one is familiar with from mathematics.
They are:

Operator Description
+ Addition
- Substraction
* Multiplication
/ Division
% Modulus
++ Increment by one
-- Decrement by one

The modulus operator gives the remainder of a division of two values: For
example:
x = 10 % 4; will give the value of 2 to x. Let us look at an example:

<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 50;
var y = 10;

document.write("x + y = ");
result = x + y;
document.write(result);
document.write("<br>");
document.write("x - y = ");
result = x - y;
document.write(result);
document.write("<br>");
document.write("x % y = ");
result = x % y;
document.write(result);
</script>
</body>
</html>

The output is 60, 40 and 0 respectively for the three arithmetic operations done
in the above program. Note that entire script was written within the body of the
html page. The values are calculated in result variable and are separated from
the value of each equation by using the <br> tag of html.

Relational and comparison operators (== , !=, >, <, >=, <= )

Two expressions can be compared using relational and equality operators. The
result of such an operation is either true or false. The relational operators in
JavaScript are:

Operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Let us look at an example:

<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 50;
var y = 10;

document.write("Checking if variables are equal");


result = x == y;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>

The assignment operator (=) is not the same as the relational operator (= =).
One assigns the value on the right hand side to the variable on the left and the
other compares whether values on both sides of the operator are equal. The
answer for the above program will be false. Try with the other operators and
see the result.

Logical operators (!, && , ||)

The operators are not, and, or.

<html>
<body>
<script language ="javascript" type="text/javascript">
<!--
var x = true;
var y = false;
document.write("And operation");
result = x && y;
document.write("<br>");
document.write(result);
document.write("<br>");
document.write("Or operation");
result = x || y;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>

The result will be false and true.


The logical operators && and!! are used when evaluating two expressions to
obtain a single relational result. The && is equivalent to the Boolean logical
operation AND which has the following truth table.

x y x && y
True True True
True False False
False True False
False False False
The || logical operator is equivalent to the Boolean logical operation OR which
has the following truth table.

x y x || y
True True True
True False True
False True True
False False False

Conditional operator (?)

The conditional operator returns one value if the expression evaluates to true
and a different one if the expression evaluates to false. Its syntax is:

Condition ? result1 : result2

This is similar to using the IF condition. We will discuss this in the controls
chapter.

For now:

9==7?5:3 will give the result 3 because 9


and 7 are not equal

7==6+1?5:3 will give the result 5

9 > 8 ? Y: N will give the result Y

Let us look at an example of this operator.

<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 9;
var y = 11;
var Y = "Yes";
var N = "No";
document.write("Condition operation");
result = (x > y) ? Y: N;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>

The result will be no 9 is less than 11. Reverse the query and see the result.
Bitwise operators (&, |, ^ , ~ , << , >> , >>>)

Modify variables considering the bit patterns representing the values they
store.

Operator Equivalent Description


& AND Boolean AND
operation on
each bit of its
integer
arguments.
| OR Boolean OR
operation on each
bit of its integer
arguments.
^ XOR Boolean exclusive
OR operation on
each bit of its
integer arguments.
~ NOT Unary operator and
operates by
reversing all the
bits in the operand.

More bitwise operators in the table below:

<< Left Shift Moves all the bits


in its first
operand to the left
by the number of
places specified
in the second
operand. New
bits are filled
with zeros.
>> Right Shift The left operand’s
value is moved
right by the number
of bits specified by
the right operand
>>> Right Shift with Bits shifted in on
Zero the left are always
zero.

Let us look at an example:

<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 9;
var y = 11;
document.write("& operation");
result = x & y;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>

The result will be 9. Now try the other operators with the same numbers.

Other assignment operators

In addition to the = assignment operator there are other operators such as the
following:

+ = for example: x+= a This means x = x+ a

- = for example: x-= a This means x = x – a


*= for example: x*= a This means x = x * a

/= for example x/= a This means x = x/a

%= for example x%=a This means x = x% a

typeof Operator

The typeof operator is a unary operator. It is placed before its single operand,
which can be of any type.

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.

<html>
<body>
<script language ="javascript" type="text/javascript">
<!--
var x = 9;
document.write("Result is");
result = (typeof x == "string" ? "x is string" :"x is
numeric");
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>

The result in this case will be x is numeric.

Now try the code with a string.


Chapter 4. Conditions
Conditions are an important part of programming. It allows the program to
jump to other points as a result of the state of the condition. Like in other
languages, JavaScript uses “IF” as a condition.

If the condition is true, a certain is action done otherwise another set of actions
will be done.

Therefore, we have If, If. Else and third option in JavaScript is If..else if…
statements.

Let us look at an example:

<html>
<body>
<script language ="javascript" type="text/javascript">
var grade = 87;
if ((grade > 90) && (grade <=100))
{
document.write("Your grade is A");
}
else if ((grade >= 80) && (grade < 90))
{
document.write("Your grade is B");
}
else if
((grade >=70) && (grade < 80))
{
document.write("Your grade is C");
}
else
{
document.write (" Your grade is F");
}
</script>
</body>
</html>
In the example above we have used all three to demonstrate the grading of a
particular subject. The program starts with a ‘If’ condition followed by a ‘else
if’. Finally, if none of the grade options were relevant the grade would be a ‘F’
by virtue of the last ‘else’ condition.

One must not forget to put { } brackets after statements. In this example there
are two conditions to satisfy and they are joined together by an and operator
(&&). Both conditions have to be true to run the statements enclosed within {}.

JavaScript does not require the semicolon after each statement but out of habit
from other languages it is best to keep the convention especially if one
programs in multiple languages.

Another way of doing a condition in several languages is the Switch statement.


This is available in JavaScript also.

Preference of which is better or appropriate is left to each programmer.


Conditions in this book will be with ‘If’ statements.

switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

The format above is used by the switch statement. The break states for each
case that is being evaluated the statements are complete.

Using a switch statement an expression is evaluated and several different


statements will be executed based on the value of the expression. If there is no
case matching the value of the expression, a default condition will be used to
display a result.

Let us look at an example.

<html>
<body>
<script language ="javascript" type="text/javascript">
var grade = 'A';
switch (grade)
{
case 'A': document.write ("Excellent");
break;
case 'B': document.write ("Good");
break;
case 'C': document.write ("Satisfactory");
break;
default: document.write("Failed");
}
</script>
</body>
</html>

If the break is missing for each case above all the values in the document.write
() will be printed on the screen.

In this case the expression we are checking happens to be a character. This


value within the switch () can also be a number.

The choice of using an ‘if’ versus a switch is up to the programmer and in


many cases it is a matter of preference.

Exercise:

1. Write a program that will display the temperature in degrees Celsius and
Fahrenheit based on user choice.

2. Continue the program given in this chapter for grade allocation for grades
between (50,60) and (60,70).

3. Write a program that will divide two numbers if the divisor is not zero.

4. Write a program that compare three inputs a, b and c and computes the
following expression (a*b) / c.
Chapter 5. Loops
Loop like conditions are a very important of programming languages. Often
they go together. The idea behind the loop is to do something repeatedly until a
situation arises to exit the process. There are three types of loops to be
considered in JavaScript and they are- While, Do-While and For.

The objective of while loop is to execute something as long as the condition


is true. If the condition is false, the loop will be exited.

Let us look at an example:

<html>
<body>
<script language ="javascript" type="text/javascript">
var count =0;
while (count < 10)
{
document.write(count);
count = count + 1;
}
</script>
</body>
</html>

Here the output will be 0..9. The loop of counting at rate of 1 will end when
count reaches 10 and breaks the condition.

The do-while loop is similar to the while loop except that the check is done at
the end of the loop. This means that the loop will be executed at least one-time
even if the condition is false.

<html>
<body>
<script language ="javascript" type="text/javascript">
var count = 0;
do {
document.write(count);
count = count + 1;

}while (count < 10);


</script>
</body>
</html>

Here the output will be 0…9 just like with the while loop. Change the count to
10 and run the code again. It will give the output 10. The condition has to be
tested has to be tested at least once.

The for loop contains three parts. First is the initialization of the loop, second
the test of the condition and then third is the iteration.

An example is a as follows: for (count=0; count <10; count++)

Thus the code will look like this:

<html>
<body>
<script language ="javascript" type="text/javascript">
for(count=0;count<10;count++)
{
document.write(count);
}
</script>
</body>
</html>

There is a loop called for-in in JavaScript. This is used to deal with objects. It
will be discussed in the chapter on objects.

The term break came up with switch. Let us look at an example:

<html>
<body>
<script language ="javascript" type="text/javascript">
var count =0;
while (count < 10)
{
document.write(count);

count = count + 1;
if (count==5)
{
break;
}
}
</script>
</body>
</html>

The break statement will stop the count at 4 and the output will be 0…4.

The continue statement tells to immediately start the next iteration of the loop
and skip the remaining code block. At continue statement the program flow
moves to the loop check expression immediately and if the condition remains
true, the next iteration begins. If condition is false, the loop is exited.

<html>
<body>
<script language ="javascript" type="text/javascript">
var count = 0;
while (count < 10)
{
document.write(count);
count = count + 1;
if (count == 4)
{
continue;
}
}
</script>
</body>
</html>

The output will be 0…9.


Chapter 6. Functions
Functions are common in all programming languages. It helps to make code
manageable, more readable and decrease the lines of code by reusing code for
common tasks.

Functions have names when they are defined. They also have parameters to be
put inside the brackets (). Thus if we have a function called test then we write
it as – test().

The brackets may contain parameters or left blank. The basic syntax for using a
function is as follows:

<html>
<body>
<script language ="javascript" type="text/javascript">
function test (parameters)
{
Statements
}
</script>
</body>
</html>

A function is called from other parts of the program by just calling its name.
Let us look at an example.

<html>
<head>
<script language ="javascript" type="text/javascript">
function first()
{
alert ("Hello World");
}
</script>
</head>
<body>
<script>

document.write(first());
</script>
</body>
</html>

Running this code will bring up a dialog box with the message Hello World.
But as soon it is closed the word undefined might be shown on the screen. This
is because this function does not have any parameters and does not return
anything. Undefined is a type in JavaScript and the sole value of this type is
Undefined value. One of the best ways to call this function would be through a
button on form. The document.write form is not able to get anything to write as
the message is in the alert box and not transferred to it.

Let us look into functions with parameters.

<html>
<head>
<script language ="javascript" type="text/javascript">
function first(name)
{
var y = name;
return y;
}
</script>
</head>
<body>
<script>
var x;
x= first('John');
document.write(x);
</script>
</body>
</html>
In this example it will print the name John. Here in the function the term return,
sends back the value to the calling point for printing. Thus when having
parameters, the return will be required.

Like in all languages functions can be nested. Functions can be defined


dynamically using a function constructor.

Let us look at how they are defined.

<script type="text/javascript">
var variablename = new Function(Arg1, Arg2..., "Function
Body");
</script>

The function constructor can take any number of string arguments. The last
argument is the body of the function – and can contain any relevant JavaScript
statements, separated from each other by semicolons.

The function constructor is not passed any argument that specifies a name for
the function it creates. The function created by the function constructor are
referred to as anonymous functions.

Let us look at an example:

<html>
<head>
<script type="text/javascript">
var func = function(x,y){ return x*y };
function secondFunction(){
var result;
result = func(10,20);
return result;
}
</script>
</head>
<body>
<script>
var x = secondFunction();
document.write(x);
</script>
</body>
</html>

In this code there is a small change to the way document.write was used. A
variable x takes the returned value of the secondFunction and then
document.write is used to print x and not the function directly. If the function is
put between the brackets it is possible to get the correct answer but the word
undefined will follow.
Chapter 7. Events
In the last chapter functions were introduced and it could be seen that printing
them out seems to lead an undefined message. One work around was shown in
the last example and another way would be call functions through forms or
buttons. That leads to this topic.

It is perhaps the most important topic for this subject because like programs
such as Visual Basic, Visual C++, Visual J++ etc. JavaScript plays a visual
role from the user point of view. The internet is a prime example of a visual
product where buttons are pressed, files are dragged, drop down menus etc.
Thus the term events.

An event is something that is created explicitly or implicitly. Clicking a button


as in a form is an example of an event. Loading of a page is an event. Placing
mouse over a button or area or moving a mouse are all examples of events. In
response to an event there can be some actions expected from the program.
Events are a part of the Document Object Model (DOM) and every html
element contains a set of events which can trigger JavaScript Code.

From the last chapter we could have called the functions from a button click.
Let us look at the most common events used on a web page.

Onload of a page:

<html>
<head>
<script type="text/javascript">
function Hello() {
document.write ("Hello World")
}
</script>
</head>
<body onLoad=Hello()>
example of onload event
</body>
</html>
This will call the function Hello and when the page has loaded it will show
Hello World. In explorer you may see the words example of onload event
before you hit allow blocked content.

Onclick event:

<html>
<head>
<script type="text/javascript">
function Hello() {
document.write ("Hello World")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="Hello()" value="Click this
button for the message">
</form>
</body>
</html>

In this example html was used to create a button and the value will give the text
shown on the button and this will call function hello to give its result. Function
Hello can be replaced by any other function.

Onsubmit:

In this event there are two parts. One part is an html form written in html and
then function that will test the contents of the html page provided. Let us look at
the html page first.

<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.write("Name must be filled out");
return false;
}

}
</script>
</head>
<body>
<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

This is a form that asks for a name and if no name or character is entered, then
it will write the message that name has to be entered. Forms that are based on
server side languages will have to go the server for validation.

Onmouseover or onmouseout:

<html><body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">Mouse over this
text</h1>
</body></html>

In the code above the words will turn red when the mouse is over the text and
black when the mouse moves from the text.

The following is a list of other events defined in JavaScript. This is not an


exhaustive list.
Offline Triggers when the document
goes offline.
Onabort Triggers on an abort event
onblur Triggers when the window
loses focus.
onchange Triggers when an element
changes.
onclick Triggers on a mouse click.
ondrag Triggers when an element is
dragged.
ondragend Triggers at the end of a drag.
ondragenter Triggers when an element
has been dragged to a valid
drop target.
ondragleave Triggers when an element
leaves a valid drop target.
ondragover Triggers when an element is
being dragged over a valid
drop target.
ondragstart Triggers at the start of a drag
operation.
ondrop Triggers when dragged
element is being dropped.
onerror Triggers when an error
occur.
onfocus Triggers when the window
gets focus.
onformchange Triggers when a form
changes.
onforminput Triggers when a form gets
user input.
onhaschange Triggers when the document
has change.
oninput Triggers when an element
gets user input.
oninvalid Triggers when an element is
invalid.
onkeydown Triggers when a key is
pressed.
onkeypress Triggers when a key is
pressed and released.
onkeyup Triggers when a key is
released.
onload Triggers when the document
loads
onloadeddata Triggers when media data is
loaded.
onloadstart Triggers when the browser
starts to load the media data.
onmessage Triggers when the message is
triggered.
onmousedown Triggers when a mouse
button is pressed.
onmousemove Triggers when the mouse
pointer moves.

onmouseout Triggers when the mouse


pointer moves out of an
element.
onmouseover Triggers when the mouse
pointer moves over an
element.
onmouseup Triggers when a mouse
button is released.
onoffline Triggers when the document
goes offline.
ononline Triggers when the document
comes online.
onpagehide Triggers when the window
is hidden.
onpageshow Triggers when the window
becomes visible.
onpause Triggers when media data is
paused.
onplay Triggers when media data is
going to start playing.
onplaying Triggers when media data
has started playing.
onresize Triggers when the window
is resized.
onscroll Triggers when an element’s
scrollbar is being scrolled.
onselect Triggers when an element is
selected.
onstalled Triggers when there is an
error in fetching media data.
onstorage Triggers when a document
loads.
onsubmit Triggers when a form is
submitted.
onsuspend Triggers when the browser
stopped before entire media
file was fetched.
ontimeupdate Triggers when media
changes its playing position.

onundo Triggers when a document


performs an undo.
onunload Triggers when the user
leaves the document.
onvolumechange Triggers when media
changes the volume and
when the volume is set to
mute.
onwaiting Triggers when media has
stopped playing but
expected to resume.
Chapter 8. Objects
JavaScript is a visual language because of its use in the biggest marketing tool
of these times which is the internet. In this manner it is similar to other visual
languages. It is also an object orient programming language like C++, Java etc
though one could argue that it is not that developed like these languages.

The fact that it is a OOP language means it has characteristics such as the
following:

Encapsulation: ability to store related information, whether data or methods.


Aggregation: ability to store one object inside another object.
Inheritance: ability of a class to rely upon another class(es)for some of its
properties and methods.
Polymorphism: ability to write one function or method that works in a variety
of different ways.

Objects have attributes (like characters) and methods. Objects can be user
defined. The attributes of an object in JavaScript can be of three data types or
can be other objects as well. Like the variables the attributes in the form of
variables can be used internally or all across the program (global) of the
webpage.

object.objectproperty = propertyvalue; ( is the syntax for attribute for an


object)

Methods are by which an object does something or something is done to it. The
difference between a function and a method is that -method is always tied to an
object.

The method for an object can be called by using the "this" keyword.

The new operator is used to create an instance of an object. The new operator
is followed by a constructor method. For example:
new car = new Array("Nissan","Toyota", "GM");

A constructor is a function that creates and initializes an object. The


constructor in JavaScript is called Object() to build the object. The return
value of Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to
the object are not variables and are not defined with the var keyword

<html>
<head>
<title>Objects</title>
<script type="text/javascript">
var car = new Object(); // Create the object
car.make = "Nissan"; // Assign properties to the object
car.name = "Pathfinder";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
</script>
</body>
</html>

Here the Object() constructor used to define a new object and assign to it two
attributes which are make and name. They are later printed out.

<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function car(make,name){
this.make = make;
this.name = name;
}
</script>
</head>
<body>
<script type="text/javascript">
var car = new car("Nissan", "Pathfinder");
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
</script>
</body>
</html>
In the example above an object has been created using a user defined function.
This is a user defined function and the "this" keyword is used to refer to the
object.

<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function price(value){
this.price =value;
}
function car(make,name){
this.make = make;
this.name = name;
this.price = price;
}
</script>
</head>
<body>
<script type="text/javascript">
var car = new car("Nissan", "Pathfinder");
car.price(20000);
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
document.write("Car price is:" + car.price + "<br>");
</script>
</body>
</html>
Here a function price has been created followed by the car function. Object is
created from the car function and price added. The method price created first
has been added to the car function as a new property of car.

The ‘with’ keyword is used as a kind of shorthand for referencing an object's


properties or methods. The properties and methods for the object can be used
without naming the object.

So in the above example we can write the function price as follows:

function price(value){
with this{
price =value;
}}

We can rewrite the code above as follows:

<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function price(value){
with (this){
price =value;
}
}
function car(make,name){
this.make = make;
this.name = name;
this.price = price;
}
</script>
</head>
<body>
<script type="text/javascript">
var car = new car("Nissan", "Pathfinder");
car.price(20000);
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
document.write("Car price is:" + car.price + "<br>");
</script>
</body>
</html>

The only change is in the function price. The programmer can choose either
style to deal with objects from functions. However, the purpose of the "with"
keyword should now be clear.

Exercise:

1. Create a function called book that has four parameters- name, author,
subject, year. Print out the values for these using an object called book.

2. Use the "with" keyword in the above code.


Chapter 9. Numbers
The number object can be created as follows:

var n = new Number(number);

Numbers have some properties. Let us look at an example:

<html>
<head>
<script type="text/javascript">
function showValue()
{
var val1 = Number.MAX_VALUE;
var val2 = Number.MIN_VALUE;
var val3 = 10;
var val4 = Number.NEGATIVE_INFINITY;
var val5 = Number.POSITIVE_INFINITY;

if ((val3<0 ) || (val3 >=10)){


val3 = Number.NAN;
document.write("The value should be between 0 and 9
inclusive" + "<br>");
}
document.write(val1 + "<br>");
document.write(val2 + "<br>");
document.write(val4 + "<br>");
document.write(val5 + "<br>");
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me"
onclick="showValue();" />
</form>
</body></html>
In the above code there are five properties of numbers shown and they are,
NAN, MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY,
POSITIVE_INFINITY. A button has been used to get the results in the above
code.

<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function car(make,name){
this.make = make;
this.name = name;
}
</script>
</head>
<body>
<script type="text/javascript">
var mycar = new car("Nissan", "Pathfinder");
car.prototype.price=null;
mycar.price= 20000;
document.write("Car make is : " + mycar.make + "<br>");
document.write("Car name is : " + mycar.name + "<br>");
document.write("Car price is:" + mycar.price + "<br>");
</script>
</body>
</html>

Here we are adding a new property to the object using a number property
called prototype. The code is the same as that objects in the previous chapter.
The difference is the prototype keyword used to introduce a new property
price into the object car referenced by mycar and then we add the value later to
print out the result.

The next property of number is a constructor. It returns a reference to the


number function that created the prototype reference. For example:
number.contructor(); It will return the function that created this objects
instance. Let us look at this code:

<html>
<body>
<script type="text/javascript">
var num = new Number(123);
document.write("num.constructor() is : " +
num.constructor);
</script></body></html>
It will return an output: num.constructor() is : function Number() { [native
code] }

Number object has properties as seen so far and therefore like objects it has
methods also. They are:

toExponential() - this forces a number to be displayed in its exponential form.

toFixed() - formats a number with a specific number of digits to the right of the
decimal point

toLocaleString() - gives a string value of the current number.

toPrecision() - tells how many digits to display for a number.

toString() - gives string representation of number.

valueOf() - gives the number value.

<html>
<head>
<title>Javascript Methods</title>
</head>
<body>
<script type="text/javascript">
var num=123.5678;
var val = num.toExponential();
document.write("num.toExponential() is : " + val );
document.write("<br />");
val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");
val = num.toFixed();
document.write("to_fixed : " + val );
document.write("<br />");
val = num.toFixed(2);
document.write("to_fixed : " + val );
document.write("<br />");
</script>
</body>
</html>

The output of this would be as follows:

num.toExponential() is : 1.235678e+2
num.toExponential(4) is : 1.2357e+2
to_fixed : 124
to_fixed : 123.57

It should be noticed the difference between first line and second line is the
precision after the decimal point and the same case for lines three and four.

<html>
<head>
<title>Javascript Methods</title>
</head>
<body>
<script type="text/javascript">
var num=123.5678;
var val = num.toLocaleString();
document.write("num.toLocaleString is : " + val );
document.write("<br />");
var val = num.toPrecision(3);
document.write("num.toPrecision is : " + val );
document.write("<br />");
var val = num.toString();
document.write("num.toString is : " + val );
document.write("<br />");
var val = num.valueOf();
document.write("num.valueOf() is : " + val );
document.write("<br />");
</script>
</body>
</html>

The output of this is as follows:

num.toLocaleString is : 123.568
num.toPrecision is : 124
num.toString is : 123.5678
num.valueOf() is : 123.5678
Chapter 10. Boolean
Boolean object has the following properties:

Constructor - Returns reference to the Boolean function that created the object.

Prototype - Similar to the number object it allows for the addition of


properties to the object.

We use the following syntax to create Boolean objects:

var val = new Boolean(value);

<html>
<head>
<title>JavaScript constructor() </title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is : " +
bool.constructor);
</script>
</body>
</html>

The output of this code will be similar to the constructor method output for
number objects and is as follows:

bool.constructor() is : function Boolean() { [native code] }

Boolean object has the following methods:

toSource() - gives a string containing the source of the Boolean object.

toString() - gives either true or false according to the state of the object.
valueOf () - gives the primitive value of the Boolean object.

<html>
<head>
<title>Boolean Methods</title>
</head>
<body>
<script type="text/javascript">
function car(make,name)
{
this.make = make;
this.name = name;
}
var mycar = new car("Nissan","Pathfinder");
var x = new Boolean(true);
document.write("mycar.toSource() is : " +
mycar.toSource());
document.write("x.toString() is : "+ x.toString() + "<br>");
document.write( "x.valueOf is : " + x.valueOf() + "<br>");
</script>
</body>
</html>

The output of the above code will be as follows:

({Make:"Nissan", Name:"Pathfinder"})

x.toString() is : true

x.valueOf is : true
Chapter 11. Strings
The string object can be initiated as follows:

var name = new String(string);

It has the following properties:

Constructor – gives a reference to the string function which created the object

Length – gives the length of a string

Prototype – similar to the cases of number and Boolean allows to add


properties to an object.

<html>
<head>
<title>String length</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "Hello, this is how to find the length
of a string." );
document.write("str.length is:" + str.length + "<br>");
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>

Here the output would be fifty (50) for the length of the string and similar to
constructor outputs for number and string will be as follows:

str.length is: 50
str.constructor is:function String() { [native code] }
String methods (not exhaustive) are as follows

charAt() – gives the character at a given index

charCodeAt() – gives a number indicating Unicode value of the character at the


given index.

concat()- adds the text of two strings.

IndexOf() – gives the index within the calling String object for the first
occurrence of a specified value.

lastIndexOf() – gives the index within the calling String object

localeCompare()- gives a number showing if a reference string comes before


or after or is the same as the given string in sorted order.

match()- is used to match a regular expression with a string.

replace() - is used to find a match between a regular expression and a string


and top replace a matched substring with a new substring.

search() – does a search for a match between a regular expression and a


specified string.

slice() – takes a section of a string and returns a new string.

split() – splits a string into an array of strings.

substr() – gives the characters in a string beginning at the specified location


through the specified number of characters.

substring() – gives the characters in a string between two indexes.

toLowerCase() – converts to lower case.


toString() – gives a string representing the specified object.

toUpperCase() – converts to uppercase.

valueOf() – gives the primitive value of the specified object.

Let us look at some examples:

<html>
<head>
<title>String methods</title>
</head>
<body>
<script type="text/javascript">
var val = new String("Hello these are some of the methods
related to a string.");
var index = val.indexOf( "are" );
document.write("val.charAt(0):" + val.charAt(0) + "
<br>");
document.write("val.charAt(2):" + val.charAt(2) + "
<br>");
document.write("val.charCodeAt(3) is:" +
val.charCodeAt(3) + "<br>");
document.write("indexOf found String :" + index );
</script>
</body>
</html>

Here we see the use of three methods- charAt(), charCodeAt() and indexOf().
The output will look as follows:

val.charAt(0):H
val.charAt(2):l
val.charCodeAt(3) is:108
indexOf found String :12
Let us look some more examples of string methods:

<html>
<title>String Methods</title>
</head>
<body>
<script type="text/javascript">
var val = "Welcome to string methods.";
var result = val.split(" ", 3);
document.write( val + "<br>" );
var sliced = val.slice(3, -2);
document.write( sliced + "<br>" );
var val2 = val.search("th");
document.write(val2 + "<br>" );
var val3= ".";

var newstr = val.replace(val3,"!!!");


document.write( newstr + "<br>" );
</script>
</body>
</html>

The output of this will be as follows:

Welcome to string methods.


come to string method
20
Welcome to string methods!!!

<html>
<title>String Methods</title>
</head>
<body>
<script type="text/javascript">
var val = "Welcome to string methods.";
document.write("(1,2): " + val.substr(1,9) + "<br>");
document.write(val.toLowerCase( ) + "<br>");
document.write(val.toUpperCase( ) + "<br>");
var index = val.localeCompare( "XYZ" );
document.write("localeCompare first :" + index );
</script>
</body>
</html>

The output is as follows:

(1,2): elcome to
welcome to string methods.
WELCOME TO STRING METHODS.
localeCompare first :-1

There are some string methods that return a copy of the string enclosed within a
html tag. They are as follows:

anchor() - creates an html anchor to be used as a hypertext target.

big() - creates a string to be displayed in a big font.

blink () - creates a string to blink.

bold() - creates a string to be bold.

fixed() - creates a string in fixed pitch font.

fontcolor() -creates a string in specific color.

fontsize() - creates a string in a particular font size.

italics() - creates a string in italics

link() - creates a html link that requests another page.

small() -creates a string to be displayed in small font.


strike() - creates a string to be displayed as struck out text.

sub() - creates a string to be shown as a subscript.

sup() - creates a string to be shown as a superscript.

<html>
<body>
<script type="text/javascript">
var val = new String("String methods");
document.write(val.big() + "<br>");
document.write(val.anchor()+ "<br>");
document.write(val.fontcolor("blue")+ "<br>");
document.write(val.bold() + "<br>");
document.write(val.fontsize(7) + "<br>");
</script>
</body>
</html>

Instead of document.write try alert() and see if the result looks different. Say
for example type alert(val.bold());

In a similar way try out the rest of the methods shown above.
Chapter 12. Arrays
An array stores multiple data of the same type in the form rows and columns.
Yes, like a matrix in math.

In JavaScript we use the following to create an array.

var car = new Array(“Nissan", "Toyota", "GM" );

In an array the first element is given the index 0. So the above is an array of
size 3 but numbered from 0 through 2.

Thus car[0] = Nissan car[1] = Toyota and car[2] = GM

Array in JavaScript have the following properties:

Constructor - gives a reference to the array function that created the object.

Index - shows the index of the match in the string.

Input - a property in an array created by regular expression matches.

Length - gives the number of elements in an array.

Prototype- used to add properties to an object.

<html>
<body>
<script type="text/javascript">
var car = new Array( "Nissan", "Toyota", "GM" );
document.write("car.constructor is:" + car.constructor + "
<br>");
document.write("car.length is:" + car.length + "<br>");
</script>
</body>
</html>
The output will be as follows:

car.constructor is:function Array() { [native code] }


car.length is:3

The following are the methods associated with arrays in JavaScript.

concat() - joins two arrays and gives the resulting array.

every() - gives a value of true if every element in an array passes a certain


testing function.

filter() - creates a new array with all the elements of existing array for which
the filtering function holds true.

forEach() - calls a function for each element in the array.

indexOf() - Gives the first least index of an element in the array equal to a
given value or -1 if none is found.

join() -all elements of an array are converted to string.

lastIndexOf() - gives the last greatest index of an element within the array
equal to the given value or -1 if none is found.

map() - gives a new array with the results of calling a function on every
element of the array.

pop() - deletes the last element from an array and returns the element.

push() - adds an element to the end of an array and gives the length of the array.

reduce() - apply a function on two values of the array at the same time to
reduce it to a single value

reduceRight() - apply a function on two values of the array from right to left to
reduce it to a single value.

reverse() - reverses the order of elements in an array.

shift() - removes the first element from an array and returns that element.

slice() - takes a section of an array and returns a new array.

some() - gives true if at least one element in the array satisfies a testing
function.

toSource() - shows the source code of an object.

sort() - sorts the elements of an array.

splice() - adds and removes elements from an array.

toString() - gives a string representing the array and its elements.

unshift()- adds one or more elements to the front of an array and returns the
new length of the array.

<html>
<head>
<title>Array Methods</title>
</head>
<body>
<script type="text/javascript">
var car = ["Nissan", "Toyota", "GM"];
var car2 = ["Hyundai","VW","Suzuki"];
var carlist = car.concat(car2);
document.write("carlist : " + carlist + "<br>");
var val = "Mazda";
document.write(" New carlist has : " + carlist.push(val) +
"<br>");
document.write("and the new carlist : " + carlist.reverse()
+ "<br>");
</script>
</body>
</html>

The above code demonstrates the concat, push and reverse methods. First two
lists are added together. The size of the two arrays are not important in this
case as the new list is being appended to the first list. We are adding a new
element and that will go to the end of the list and finally the list is being printed
in a reverse manner.

The output looks as follows:

carlist : Nissan,Toyota,GM,Hyundai,VW,Suzuki
New carlist has : 7
and the new carlist : Nissan,Toyota,GM,Hyundai,VW,Suzuki,Mazda
and the new carlist in reverse order is :
Mazda,Suzuki,VW,Hyundai,GM,Toyota,Nissan

<html>
<head>
<title>Array Methods</title>
</head>
<body>
<script type="text/javascript">
var index = [12, 5, 8, 130, 44];
document.write("sort is : " + index.sort() + "<br>" );
document.write("index is : " + index.lastIndexOf(8) + "
<br>" );
document.write("slice at index 2" + index.slice(2) + "
<br>" );
document.write("splice at index 2 : " + index.splice(2) + "
<br>" );
document.write("shift : " + index.shift() + "<br>" );
</script>
</body>
</html>
The methods shown above are sort, lastIndexOf, slice, splice and shift and the
output will look as follows:

sort is : 12,130,44,5,8
index is : 4
slice at index 244,5,8
splice at index 2 : 44,5,8
shift : 12

Let us look at some more examples:

In this example of using reduce() and reduceRight(), it has to be noted that


these functions are extensions to the JavaScript standard and therefore may not
work without some effort on some browsers.

The two are related in terms of what they do. The difference is the direction.
Let us take an example of three numbers 100, 2 and 25 in an array.
So in the case of reduce the direction is from left to right and the opposite
(right to left) for reduceRight.

Let us look at the following code.

<html>
<head>
<script language="JavaScript">
var answer = [100,2,25].reduceRight(function(a, b){ return
a / b; });
document.write("The answer is : " + answer);
</script>
</head>
<body>
</body>
</html>

Here the answer will be 0.125.

That is 25/2 = 12.5 / 100 = 0.125.


Now let us look at the following code.

<html>
<head>
<script language="JavaScript">
var total = [100,2,25].reduce(function(a, b){ return a / b;
});
document.write("total is : " + total );
</script>
</head>
<body>
</body>
</html>

The code is the same except for the reduce instead of reduceRight.

The answer will be 2.

That is 100 / 2 = 50 followed by 50 / 25 = 2.


Chapter 13. Date
A date object in JavaScript is created with new Date().

The properties of the date object are as follows:

Constructor - gives the function that created the date object.

Prototype - allows properties to be added to objects.

When a date object is created with new Date() without anything in the brackets
then the date object is set the current date and time on the system.

Milliseconds: Placing 10000 within the brackets creates a date that represents
ten seconds past midnight on 1/1/70.
Datestring: a string representation of the date, in the format accepted by the
Date.parse() method will be taken as the value of the object.
Arguments: The date object can take several other arguments inside the bracket
such as:
year: Integer value representing the year in full format. Ex: 2017
month: Integer value representing the month, beginning with 0 for January.
date: Integer value representing the day of the month.
hour: Integer value representing the hour of the day in 24-hour format.
minute: Integer value representing the minute segment of a time reading.
second: Integer value representing the second segment of a time reading.
millisecond: Integer value representing the millisecond segment of a time
reading.

<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">

var val = Date();


document.write("Date and Time : " + val );
</script>
</body>
</html>

This will give the setting on the system on which the browser is open.

The methods associated with the date object are as follows:

getDate() - returns the default system date and time

getDay() - returns day based on system date and time.

getFullYear() - returns the year based on system date and time.

getHours() - returns the hours based on system date and time.

getMilliseconds() - returns the milliseconds based on system date and time.

getMinutes() - returns the minutes based on the system date and time.

getMonth() - returns the month based on the system date and time.

getSeconds() - returns the seconds based on the system date and time.

getTime() - returns the numeric value of the specified date as the number of
milliseconds since January 1, 1970.

getTimezoneOffset() - returns the time-zone offset in minutes for the current


locale.

getUTCDate() - returns the day (date) of the month in the specified date
according to universal time.
getUTCDay() - returns the day of the week in the specified date according to
universal time.

getUTCFullYear() - returns the year in the specified date according to


universal time.

getUTCHours() - returns the hours in the specified date according to universal


time.
getUTCMilliseconds() - returns the milliseconds in the specified date
according to universal time.

getUTCMinutes() - returns the minutes in the specified date according to


universal time.

getUTCMonth() - gives the month in the specified date according to universal


time.

getUTCSeconds() - gives the seconds in the specified date according to


universal time.

SetDate() - sets the day of the month for a specified date according to local
time.

setFullYear() - sets the full year for a specified date according to local time.

setHours() - sets the hours for a specified date according to local time.

setMilliseconds() - sets the milliseconds for a specified date according to


local time.

setMinutes() - sets the minutes for a specified date according to local time.

setMonth() - sets the month for a specified date according to local time.

setSeconds() - sets the seconds for a specified date according to local time.

setTime() - sets the Date object to the time represented by a number of


milliseconds since January 1, 1970, 00:00:00 UTC.

setUTCDate() - sets the day of the month for a specified date according to
universal time.

setUTCFullYear() - sets the full year for a specified date according to


universal time.

setUTCHours() - sets the hour for a specified date according to universal time.

setUTCMilliseconds() - sets the milliseconds for a specified date according to


universal time.

setUTCMinutes() - sets the minutes for a specified date according to universal


time.

setUTCMonth() - sets the month for a specified date according to universal


time.

setUTCSeconds() - sets the seconds for a specified date according to universal


time.

toDateString() - returns the date portion of the date as a string.

toLocaleDateString() - returns the date portion of the date as a string as per


locale conventions.

toLocaleFormat() - converts a date to a string using a format string.

toLocaleString() - converts a date to a string using the current locale


conventions.

toLocaleTimeString() - returns time part of the date as a string using current


locale's conventions.

toSource() - Returns a string representing the source for an equivalent Date


object; you can use this value to create a new object.
toString() - Returns a string representing the date object.

toTimeString() - Returns the time portion of the date.

toUTCString() - Converts a date to a string using universal time convention.

valueOf() - gives the primitive value of the date object.

The above may not be an exhaustive list as developments are made in


JavaScript but does apply at the time of writing this book. Let us look at some
examples of code:

<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
document.write("getDate() : " + val.getDate() + "<br>" );
document.write("getDay() : " + val.getDay() + "<br>");
document.write("getFullYear() : " + val.getFullYear() + "
<br>");
document.write("getHours() : " + val.getHours()+ "<br>");
</script>
</body>
</html>

Notice that we have defined a date of 25 December 2016 at 10:10 pm in the


date object. This happened to be a Sunday so the day will show as 0. 0 stands
for Sunday and thus Monday will be 1 and so forth until Saturday will be 7.

<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
document.write("getDate() : " + val.getDate() + "<br>" );
document.write("getDay() : " + val.getDay() + "<br>");
document.write("getFullYear() : " + val.getFullYear() + "
<br>");
document.write("getHours() : " + val.getHours()+ "<br>");
document.write("getMilliseconds() : " +
val.getMilliseconds() + "<br>");
document.write("getMinutes() : " + val.getMinutes() + "
<br>" );
document.write("getMonth() : " + val.getMonth() + "
<br>");
document.write("getSeconds() : " + val.getSeconds() + "
<br>");
document.write("getTime() : " + val.getTime() + "<br>");
document.write("getTimezoneOffset() : " +
val.getTimezoneOffset() + "<br>");
</script>
</body>
</html>

The output will be as follows:

getDate() : 25
getDay() : 0
getFullYear() : 2016
getHours() : 22
getMilliseconds() : 0
getMinutes() : 10
getMonth() : 11
getSeconds() : 0
getTime() : 1482693000000
getTimezoneOffset() : -180

Now let us look at some further examples with some of the other methods
mentioned earlier for date object.
<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
document.write("getUTCDate() : " + val.getUTCDate() + "
<br>" );
document.write("getUTCDay() : " + val.getUTCDay() + "
<br>" );
document.write("getUTCFullYear() : " +
val.getUTCFullYear() + "<br>");
document.write("getUTCHours() : " + val.getUTCHours()
+ "<br>" );
document.write("getUTCMilliseconds() : " +
val.getUTCMilliseconds() + "<br>");
document.write("getUTCMinutes() : " +
val.getUTCMinutes() + "<br>" );
document.write("getUTCMonth() : " + val.getUTCMonth()
+ "<br>");
document.write("getUTCSeconds() : " +
val.getUTCSeconds() + "<br>");
document.write("getYear() : " + val.getYear() + "<br>");
</script>
</body>
</html>

The output of the code is as follows:

getUTCDate() : 25
getUTCDay() : 0
getUTCFullYear() : 2016
getUTCHours() : 19
getUTCMilliseconds() : 0
getUTCMinutes() : 10
getUTCMonth() : 11
getUTCSeconds() : 0
getYear() : 116

Let us look at some more examples of methods related to the date object.

Here in the examples there are two variables val and val2. The first is set to a
particular date and the second is kept open to the date on the system. Note the
results for both cases.
<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
var val2 = new Date();
val.setDate( 24 );
val2.setDate( 24 );
document.write( val + "<br>");
document.write( val2 + "<br>");
val.setFullYear( 2014 );
document.write( val + "<br>" );
val.setHours( 02 );
document.write( val + "<br>" );
val2.setMonth( 2 );
document.write( val2 + "<br>");
val2.setUTCDate( 20 );
document.write( val2 + "<br>" );
</script>
</body>
</html>

The output is as follows:

Sat Dec 24 2016 22:10:00 GMT+0530


Wed May 24 2017 12:57:03 GMT+0530
Wed Dec 24 2014 22:10:00 GMT+0530
Wed Dec 24 2014 02:10:00 GMT+0530
Fri Mar 24 2017 12:57:03 GMT+0530
Mon Mar 20 2017 12:57:03 GMT+0530

In addition to the methods mentioned above the date object has two static
methods:

Date.parse() - Parses a string representation of a date and time and returns the
internal millisecond representation of that date.
Date.UTC() - Returns the millisecond representation of the specified UTC date
and time.
Let us look at an example:

<html>
<head>
<title>Date parse Method</title>
</head>
<body>
<script type="text/javascript">
var val = Date.parse( "Feb 15, 2017 23:30:00" );
document.write( "Number of milliseconds from 1970: " +
val );
</script>
</body>
</html>

The output will be as follows:

Number of milliseconds from 1970: 1487190600000

Now suppose we want to use the second method Date.UTC(). Here the year
will be in full format, month (0-11), day (1-31), hours (0-23), minutes(0,59),
seconds (0,59) and milliseconds (0,999). Let us look at an example.

<html>
<head>
<title>Date parse Method</title>
</head>
<body>
<script>
var val = Date.UTC(2016,2,15);
document.write( "Number of milliseconds from 1970: " +
val );
</script>
</body>
</html>
The output will be as follows:

Number of milliseconds from 1970: 1458000000000

The year in this example is 2016, the month February and the day 15.
Chapter 14. Actions in Math
The math object was discussed before with respect to its properties and
methods. Here we look at some more useful properties and methods using math
in JavaScript.

Let us look at some properties first:

Euler - E

LN2 - Natural logarithm of 2.

LN10 - Natural logarithm of 10.

LOG2E - Base 2 logarithm of E.

LOG10E - Base 10 logarithm of E.

PI - Ratio of the circumference of a circle to its diameter.

SQRT1_2 - Square root of 1/2.

SQRT2 - Square root of 2.

Let us look at an example that calls on some of these properties.

<html>
<body>
<script type="text/javascript">
var val = Math.E;
document.write("Property Value is :" + val + "<br>");
var val = Math.LN2;
document.write("Property Value is :" + val + "<br>");
var val = Math.LOG10E;
document.write("Property Value is :" + val + "<br>");
var val = Math.PI;
document.write("Property Value is :" + val + "<br>");
var val = Math.SQRT2;
document.write("Property Value is :" + val + "<br>");
</script></body></html>
The output will be as follows:

Property Value is :2.718281828459045


Property Value is :0.6931471805599453
Property Value is :0.4342944819032518
Property Value is :3.141592653589793
Property Value is :1.4142135623730951

Now let us look at some methods.

abs() - gives absolute value of a number.

acos() - gives the arc cosine in radians of a number.

asin() - gives the arc sine in radians of a number.

atan() - gives the arc tangent in radians of a number.

atan2() - gives the arc tangent of the quotient of its arguments.

ceil() - gives the smallest integer greater than or equal to a number.

cos() - gives the cosine of a number.

sin() - gives the sine of a number.

tan() - gives the tan of a number.

exp() - gives the value when N is the argument and E is the Euler's constant.
floor() - gives the largest integer less than or equal to a number.

log() - gives the natural logarithm value of a number n.

max() - gives the maximum number after comparing two or more numbers.

min() - gives the minimum number after comparing two or more numbers.

pow() - gives the base to exponent power.

random() - gives a random pseudo number between 0 and 1.


round() - gives a number rounded to the nearest integer.

sqrt() - gives the square root of a number.

toSource() - gives the string "Math".

Now look at an example that makes use some of these methods.

<html><body><script>
var val = Math.abs(-20);
document.write("abs() is:" + val + "<br>");
var val = Math.sqrt(20);
document.write("sqrt() is:" + val + "<br>");
var val = Math.sin(90);
document.write("sin() is:" + val + "<br>");
var val = Math.ceil(20.145);
document.write("ciel() is:" + val + "<br>");
var val = Math.exp(20);
document.write("floor() is:" + val + "<br>");
var val = Math.max(10,20,25,15,12,14,35,8);
document.write("max() is:" + val + "<br>");
var val = Math.pow(10,2);
document.write("pow() is:" + val + "<br>");
var val =Math.random();
document.write("random() is:" + val + "<br>");
var val = Math.round(20.541);
document.write("round() is:" + val + "<br>");
</script></body></html>

The output is as follows:


abs() is:20
sqrt() is:4.47213595499958
sin() is:0.8939966636005579
ciel() is:21
exp() is:485165195.4097903
max() is:35
pow() is:100
random() is:0.4441565757123287
round() is:21
Chapter 15. Regular Expressions
A common feature of any programming language is regular expression. So what
is a regular expression. One is familiar with telephone numbers and zip codes
or postal codes. They all follow a particular pattern globally. Regular
expressions can be defined by using the RegExp() constructor in JavaScript.

var val = RegExp(pattern, attributes);

A pattern is a string that specifies the pattern of the regular expression that is of
interest. Attributes are optional strings that specifies some global or multi line
matches.
Regular expressions are often seen in the form of brackets, alphabets, / or *.
Brackets have the following meaning:
[...] = Any one character between the brackets.
[^..] = Any one character not between the brackets.
[0-9] = Must be a number from 0 through 9 both being inclusive.
[a-z] = Matches any lower characters a through z.
[A-Z] = Matches any upper characters A through Z.
[a-Z] = Matches any character from lower case a through upper case Z.
While these are supersets within the brackets lower ranges can be mentioned.
For example, [0-1].
Further we have the following:
p+ = matches anything which has at least one p.
p* = matches a string which has zero or more p's.
p? = matches a string with one or more p's.
p{N} = matches any string that has a sequence of N p's.
p{3,5} = matches any string that has a sequence of three or five p's.

p{3, } = matches any string that has a sequence of at least three p's.
p($) = matches any string that has a p at the end of it.
^p = matches any string with p at the start.

[^a-zA-Z] = matches anything other than a through z and A through Z.


p.p = matches any string containing p followed by any character in turn
followed by p.
^.{2}$ = matches any string that has exactly two characters.
<b>(.*)</b> = matches any string between the bold html tags.
p(hp)* = matches any string containing a p followed by zero or more instances
of the sequence hp.
\0 = null character (\u0000)
\t = tab (\u0009)
\n = newline(\u000A)
\v = Vertical Tab(\u000B)
\f = Form feed(\u000C)
\r = Carriage Return(\u000D)
Metacharacters are alphabetical characters preceded by a backslash that when
read in combination gives a meaning. Some of the metacharacters in JavaScript
are as follows:

. = single character.

\s = a whitespace character.

\S = non whitespace character.

\d = any digit from 0 through 9.

\D = not a digit.

\w = any word character.


\W = not a word character.

[\b] = backspace.

[bfam] = matches any character in the given set.

[^bfam] = matches anything outside the given set.

(foo|ama|xyz) = matches any of the alternatives specified.

Modifiers for regular expression help to make regular expression easier to


understand. Some of them are as follows:

i = performs case insensitive matching.

m = tells if string has newline or carriage return characters.

g = finds all matches and does not stop after finding the first match.

Regular expressions has certain properties:

Constructor - gives the function that created the object.

Global - tells if the g modifier has been set or not.

ignoreCase -Specifies if the i modifier has been set.

lastIndex -The index at which to start the next match.

multiline -Specifies if m modifier has been set.

source - the text of the pattern.

<html><body><script type="text/javascript">
var val = new RegExp( "This is a regular expression." );
document.write(val.global + "<br>");
val = new RegExp(val, "g" );
document.write(val.global + "<br>");
val =new RegExp(val,"i");
document.write(val.ignoreCase + "<br>"); <script>
</body></html>
The output of the above code will be as follows:

false
true
true

RegExp.exec() and RegExp.test() methods work only if the g modifier has been
set. The lastIndex is a read write property.

<html>
<body>
<script type="text/javascript">
var val = "This is an example of a regular expression
method.";
var x = new RegExp( "example", "g" );
x.test(val);
document.write("Current Index: " + x.lastIndex + "<br>");
x.test(val);
document.write("Current Index: " + x.lastIndex + "<br>");
</script>
</body>
</html>

Methods related to regular expression are:

exec() - executes a search for a match in its string parameters.

test() - tests for a match in its string parameters.

toSource() - gives an object literal representing the specified object.

toString() - gives a string representing the object.


<html> <body> <script type="text/javascript">
var val = "This is an example of a regular expression
method.";
var x = new RegExp( "example", "g" );
x.exec(val);
document.write("Current Index: " + x.lastIndex + "<br>");
x.exec(val);
document.write("Current Index: " + x.lastIndex + "<br>");
</script>
</body></html>
Chapter 16. Refresh and Redirect
Thus far the basics of JavaScript was looked into and so it is now time to put
all these basics into some practical applications that are common on the
internet or in a webpage or website.

Let us look into how JavaScript can be used to refresh a page.

<a href="javascript:location.reload(true)"> Click to Refresh Page</a>

Here we have a link “Click to Refresh Page” which needs to be clicked to


refresh the page. Better yet the reload option can be connected any of the event
triggers seen earlier under the chapter on events.

There is a built in JavaScript feature called auto refresh which can be called
by using setTimeout(). This will auto refresh the page after a certain interval in
seconds which have to be added to that function.

<html>
<head>
<script type="text/JavaScript">
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
</script>
</head>
<body onload="JavaScript:AutoRefresh(5000);">
<img src=test.jpg>
<p>This page will refresh every 5 seconds. </p>
</body>
</html>

Here test.jpg was a picture to test if the page reloads every five seconds.

The ‘t’ indicates the auto refresh is from the server side versus client side in
the form of the cache. If the latter is the intention, then replace ‘t’ with ‘f’.
This kind of auto refreshing is only good for those webpages which have
content that is either live or changing at a fast pace. For most websites having
this feature in an opening page may not be practical.

A common feature seen on the internet is that of redirection. A link indicating


that page has moved for whatever reason.

<html>
<head>
<script type="text/javascript">
function rd() {
window.location="http://www.xyz.com";
}
</script>
</head>
<body>
<p>Click the following button, you will be redirected to
our new home page.</p>
<form>
<input type="button" value="Redirect Me" onclick="rd();"
/>
</form>
</body>
</html>

This will create a page with a button that needs to be clicked for redirection to
take place. The page will remain static until the button is pressed. It might be
more impressionable if in addition to providing a button to click the page
reloads the new website after a few seconds. The setTimeout() method in the
previous example could be used for this purpose.

<html>
<head>
<script type="text/javascript">
function rd() {
window.location="http://www.xyz.com";
}
document.write ("You will be redirected to our main page
in 5 seconds!");
setTimeout('rd()', 5000);
</script>
</head>
<body>
</body>
</html>

The choice of redirection should be limited to those times when it is absolutely


required. Internet visitors are often turned off by frequent redirection. The
dialog box came up in one or more examples in the previous chapters. But the
dialog box is a classic in JavaScript.

<html>
<head>
<script type="text/javascript">
function Hello() {
alert ("This is a dialog box");
document.write ("Hello how are you??");
}
</script>
</head>
<body>
<p>Click the following button:</p>
<form>
<input type="button" value="Click Me" onclick="Hello();"
/>
</form>
</body>
</html>

In the program after the dialog box is shown the body of the page will show the
words “Hello how are you?”. The alert() by itself was sufficient to pass the
message but what happens after the dialog box is closed? Thus when using a
dialog box with a button as in this case do not forget the body of the page needs
to have something meaningful.
<html>
<head>
<script type="text/javascript">
function gc(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
window.location="http://www.xyz.com";
return true;
}else{
return false;
}

}
</script>
</head>
<body>
<p>Click the following button: </p>
<form>
<input type="button" value="Click Me" onclick="gc();" />
</form>
</body>
</html>

Here the dialog box gives two options. If “OK” it will continue to open a page
in the program otherwise it will remain on the same page. The prompt() feature
in JavaScript allows one to enter a value into the dialog box as an input.

<html>
<head>
<script type="text/javascript">
function gv(){
var val = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + val);
}
</script>
</head>
<body>
<p>Click the following button: </p>
<form>
<input type="button" value="Click Me" onclick="gv();" />
</form>
</body>
</html>

The input box will appear after clicking the button and whatever is provided
by the user will be printed to the body of the page. The usefulness of this
method is left to the reader. Normally input in a form of a website is sent to the
server for processing.
Chapter 17. Cookies
Cookies are connected with the word sessions in internet programming.
Sessions are not part of JavaScript but other programming languages or scripts
used for making internet pages.

Cookies are text files that store some data perceived to be important from the
point of view of the server and the client.

Cookies contain five variable length fields:

Expires – tells when the cookie will expire. Leaving it blank means that cookie
will last only during the browser session of the user.

Domain- the domain name of the website

Path – The path to the web page that set the cookie. This could be left blank.

Secure – if set then a secure server will be required.

Name=Value – cookies are set and retrieved in the form of key value pairs.

Cookies are created using the document.cookie statement.

<html>
<head>
<script type="text/javascript">
document.cookie ="cookie=" + escape("This is my first
cookie");
alert(document.cookie);
</script>
</head>
</html>

The above code creates a basic cookie. Here we are trying to display the
cookie with an alert dialog box.
The output will look like this when seen in Microsoft IE Edge.

When a page is accessed the document.cookie page will automatically see if


there are any cookies created before. This process is done implicitly.

Now let us look into a way to access the cookie. We start with the
document.cookie statement as follows:

var mynewcookie = document.cookie;

Use the split() method defined in the chapter on strings and do this:

var mynewcookieparts = mynewcookie.split("=") The argument in the brackets


is the delimiter.

var cookiename = mynewcookieparts[0];

One can guess after the name we need a value for the cookie as we discussed
in the beginning of the chapter. Thus the next cookie part is:

var cookievalue = mynewcookieparts[1];

Thus there is an array of mynewcookieparts. To complete the code, we have to


unescape cookievalue as it contains the value of the cookie. Let us assume for
now that we are dealing with only a single page. The code looks as follows:
<html>
<head>
<script type="text/javascript">
document.cookie ="cookie=" + escape("This is my first
cookie");
alert(document.cookie);
</script>
<script type="text/javascript">
var mynewcookie = document.cookie;

var mynewcookieparts = mynewcookie.split("=");


var cookieName = mynewcookieparts[0];
var cookieValue = unescape(mynewcookieparts[1]);
alert(cookieName);
alert(cookieValue);
</script>
</head>
<body>
</body>
</html>

The output as seen in IE browser is as follows:

The first script had given the name of the cookie as cookie and value as my
first cookies which has now been found and displayed.

Cookies expire at the end of the browser session. If a cookie needs to be active
beyond that the expiry date needs to be included. For this purpose, let us first
create a variable for our date of expiry for the cookie.

var cdate = new Date(2017, 5,7,12,00,00); (The date of expiry here is 7th of
May at midday in the year 2017)

Like it was done in the first code for naming the cookie:

document.cookie ="cookie=" + escape("This is my first cookie");

To this the following part is added:

document.cookie ="cookie=" + escape("This is my first cookie") + ";expires="


+ cdate.toGMTString();

The code is as follows:

<html>
<head>
<script type="text/javascript">
var cdate = new Date(2017,5,7,12,00,00);
document.cookie ="cookie=" + escape("This is my first
cookie") + ";expires=" + cdate.toGMTString();
alert("cookie=" + escape("This is my first cookie") +
";expires=" + cdate.toGMTString());
</script>
</head>
</html>

The output using IE explorer will look as follows:


In the code below the cookie is deleted.

<html>
<head>
<script type="text/javascript">
var cdate = new Date();
cdate.setTime(cdate.getTime() - 86400000);
document.cookie ="cookie=" + escape("This is my first
cookie") + ";expires=" + cdate.toGMTString();
alert("cookie=" + escape("This is my first cookie") +
";expires=" + cdate.toGMTString());
</script></head></html>

The date of the cookie is kept to a past date. The number 86400000 represents
1 day in milliseconds.

In the code below multiple cookies are created and accessed.

<html>
<head>
<script type="text/javascript">
document.cookie ="cookie1=" + escape("This is my first
cookie");
document.cookie ="cookie2=" + escape("This is my second
cookie");
var first = document.cookie.indexOf("cookie1=");
var firstEnd = document.cookie.indexOf(";", first + 1);
if (firstEnd == -1) { firstEnd = document.cookie.length; }
var firstCookie =
unescape(document.cookie.substring(first+8,firstEnd));
var second = document.cookie.indexOf("cookie2=");
var secondEnd = document.cookie.indexOf(";", second + 1);
if (secondEnd == -1) { secondEnd =
document.cookie.length;}
var secondCookie =
unescape(document.cookie.substring(second+8,secondEnd));
alert(firstCookie);
alert(secondCookie);
</script>
</head>
</html>

The last two alerts will show the cookies separately. Creating two cookies is
similar to making each cookie as seen earlier. Accessing the cookies is where
the difference lies. To access each cookie, the indexOf method is used to find
where the cookie ends.

Check to see whether or not a semicolon was found by checking if firstEnd has
the value -1. If the value is -1, it means that this cookie is the last cookie and
firstEnd should be set to the last character in the document.cookie string.

Extract the value of the first cookie by taking the substring starting at the
character after "cookie1=" and ending at the semicolon. This is done with the
substring method of the String object, and the resulting substring is passed to
unescape to remove any escaped characters. The results are stored in the
variable firstCookie.

Note that first + is used as the first character of the substring;this represents the
first character after the equal sign after cookie1 (since "cookie1=" is 8
characters long).

The same process is repeated for the second cookie as shown in the code
above.

Now look at the code below:


<html>
<head>
<script type="text/javascript">
var newDate = new Date();
newDate.setTime(newDate.getTime() + 15724800000);
var firstVisit = document.cookie.indexOf("cookie3=");
if (firstVisit == -1) {
document.cookie = "cookie3=1;expires=" +
newDate.toGMTString();
window.location = "http://myurl.com/new.html"
}
document.cookie = "cookie3=1;expires=" +
newDate.toGMTString();
</script>
</head>
<body>
</body></html>

In this code a cookie called cookie3 is being searched for. If it exists, then fine
but if it does not then it is assumed that user has not visited the page before and
the user is send to another page. The purpose of this type of a redirection is
that some websites might require a user to register before continuing to browse
through their website.

In the code above 15724800000represents six months. 26 weeks * 7 days per


week * 24 hours per day * 60 minutes per hour * 60 seconds per minute * 1000
milliseconds per seconds, for a total of 15724800000 milliseconds. If the
cookie does not exist, the expiration date can be set to any number of months or
days as shown in our example.

The line if (firstVisit == -1) { } tests whether the cookie mentioned exists or
not.
Chapter 18. DHTML
Throughout the codes in this book we have used html along with
document.write to manipulate the output.

<html>
<head>
<script language="JavaScript">
var placeholder =
window.open("holder.html","placeholder","width=200,height=200");
</script>
<title>The Main Page</title>
</head>
<body onLoad="placeholder.close()">
<p>This is the main page</p>
</body>
</html>

In this script we are trying to create a 200 by 200-pixel notice saying the page
is loading before the main page is displayed. To do this two html files are
required. One for the loading message and one for the main page. The
JavaScript above is included in the html file containing the main content. Size
of the message can be changed. This kind of method could be used to send
other notice messages of relevance to the page. Both files are assumed to be in
the same directory. Also window has to be closed once opened.

Now let us create a form using JavaScript. The code will look like this.

<html>
<body>
<form method="post" action="target.html"
name="thisForm">
<input type="text" name="myText">
<select name="mySelect">
<option value="1">Link one</option>
<option value="2">Link two</option>
</select>
<br><input type="submit" value="Submit Me"></form>
</body></html>
You will get a selection of two links and the output will look like this.

Here the target link for the action in the form definition is an html file.
Normally it will be a file in a scripting language such as php or asp etc.

To access text in a text box in a form done in html you may use the following
code.

<html>
<body>
<form name="myForm">
<input type="text" name="myText">
</form>
<a href="#"
onClick="window.alert(document.myForm.myText.value);">Check
Text Field</a>
</body></html>

So if I type hello in the text box the output message from the alert will be hello
as seen below.

To copy text from one text field to the other look at the following code.

<html><body>
<form name="myForm">
Enter some Text: <input type="text" name="myText"><br>
Copy Text: <input type="text" name="copyText">
</form><a href="#"
onClick="document.myForm.copyText.value =
document.myForm.myText.value;">Copy Text Field</a>
</body></html>
This will give the following output.

A very frequent thing in forms is messages when someone enters something in a


text box and then proceeds to another text box or another form element. In the
code below as the focus moves away from the text box (by clicking anywhere
outside it) a message will pop up.

<html>
<body>
<form name="myForm">
Enter some Text: <input type="text" name="myText"
onChange="window.alert(this.value);">
</form>
</body></html>

The output will look like this.


A very common part of a form is a selection list. In the start of the chapter we
saw a selection list. The code in the table below will show to do a selection
in a form and on clicking the link it will show the selection made.

Selection options in this case is manually created. It is possible to create a


selection based on data in a database. But that is not within the scope of this
book.

<html>
<body>
<form name="myForm">
<select name="mySelect">
<option value="Link one">1</option>
<option value="Link two">2</option>
<option value="Link three">3</option>
</select>
</form>
<a href="#"
onClick="window.alert(document.myForm.mySelect.value);">Check
Selection List</a
</body></html>

The output will look as follows:


If there is a selection list already containing two options and it is required to
change that to three options using JavaScript the following code can be used to
do that. It involves a function in JavaScript which is called on clicking the link
to change the selection list options.

<html>
<body>
<script>
function list(list) {
list.length = 3;
list.options[0].text = "Link 1";
list.options[0].value = " Link Value 1";
list.options[1].text = "Link 2";

list.options[1].value = "Link Value 2";


list.options[2].text = "Link 3";
list.options[2].value = "Link Value 3";
}
</script>
<form name="myForm">
<select name="mySelect">
<option value="1">Link 1</option>
<option value="2">Link 2</option>
</select><br>
</form>
<a href="#"
onClick="list(document.myForm.mySelect);">Change the
List</a></body></html>

The output will look like this.

The following code will allow user to select from a given list and see the
selection as an alert dialog box.

<html><body>
<form name="myForm">
<select name="mySelect"
onChange="window.alert(this.value);">
<option value="First Choice">1</option>
<option value="Second Choice">2</option>
<option value="Third Choice">3</option>
</select></form> </body></html>

The output of the previous code is shown below the table. Another form
element is the radio button. In the following code JavaScript is used to access
the radio button selected.

<html>
<body>
<script language="JavaScript">
function Button() {
var buttonValue = "";
for (i = 0; i < document.myForm.myRadio.length; i++) {
if (document.myForm.myRadio[i].checked) {
buttonValue = document.myForm.myRadio[i].value;
}
}
return buttonValue;
}
</script>
<form name="myForm">
<input type="radio" name="myRadio"
value="First Button"> Button 1<br>
<input type="radio" name="myRadio"
value="Second Button"> Button 2
</form>
<a href="#" onClick="window.alert(Button());">Which
Radio Button?</a>
</body></html>

The output will look as follows:

Clicking radio button 2 will give second button. The code below will detect
the radio button clicked.

<html>
<body>
<form name="myForm">
<input type="radio" name="myRadio" value="First
Button" onClick="window.alert('First Button
selected');">Button 1<br>
<input type="radio" name="myRadio" value="Second
Button" onClick="window.alert('Second Button
selected');">Button 2
</form>
</body></html>

The output will look like this.

The following code can be used to detect the clicking of a checkbox on a form.

<html>
<body>
<form name="myForm">
<input type="checkbox" name="myCheck"
value="My Check Box"> Check Me
</form>
<a href="#"
onClick="window.alert(document.myForm.myCheck.checked
? 'Yes' : 'No');">Am I Checked?</a>
</body></html>

The resulting output will look like this.

The following code demonstrates how a choice can be changed with respect to
a check box.

<html>
<body>
<form name="myForm">
<input type="checkbox" name="myCheck"
value="My Check Box"> Check Me
</form>
<a href="#"
onClick="document.myForm.myCheck.checked =
false;">Uncheck the box</a>
</body></html>

Clicking on the uncheck the box link will change the selection from yes to no. It
is a very common feature of a form to have text boxes. To make each text box
whose info is required to be mandatory one could use the following type of
code to indicate that the text box is empty.

<html><body>
<script language="JavaScript">
function checkField(field) {
if (field.value == "") {
window.alert("You must enter a value in the field");
field.focus();
}}
</script>
<form name="myForm" action="target.html">
Text Field: <input type="text" name="myField"
onBlur="checkField(this)"><br>
<input type="submit">
</form></body></html>
The output will look as follows.

The other alternative is to wait till one clicks the submit button to check if the
needed text boxes are filled up.

<html>
<head>
<script language="JavaScript">
function check(formObj) {
var fk= true;
if (formObj.myField.value == "") {
window.alert("You must enter a value in the field");
formObj.myField.focus();
fk = false;
}
return fk;
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return check(this);">
Text Field: <input type="text" name="myField"><br>
<input type="submit">
</form>
</body></html>

In this code function is called on clicking the button and is attached to the
onSubmit part of the form action. The check function can also be added to the
onClick event of the button itself like this.

<form name="myForm" action="target.html">


Text Field: <input type="text" name="myField"><br>
<input type="button" value ="submit"
onClick="check(this.form);">
</form>

One of the common features of a form such as an online application form is the
query on a phone number. Phone numbers come in different formats across the
globe. Let us look at the following code.

<html>
<head>
<script language="JavaScript">
function checkForm(formObj) {
return checkPhone(formObj.myField.value); }
function checkPhone(phone) {
if (phone.length == 0) {
window.alert("You must provide a phone number.");
return false;
}
phone = phone.replace("-","");
phone = phone.replace(" ","");
phone = phone.replace("(","");
phone = phone.replace(")","");
phone = phone.replace(".","");
if (phone.length != 10) {
window.alert("Phone numbers must only include a 3-digit
area code and a 7-digit phone number.");
return false;
}
for (i=0; i<phone.length; i++) {
if (phone.charAt(i) < "0" || phone.charAt(i) > "9") {
window.alert("Phone numbers must only contain
numbers.");
return false;
}
}
return true;

}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return checkForm(this);">
Phone: <input type="text" name="myField"><br>
<input type="submit">
</form>
</body></html>

Now with this code if a phone number is not entered or not in the right format
the error message will come up accordingly. This code is long. Another way
phone can be verified is by using regular expressions. As mentioned in the
regular expressions chapter the first thing to do is to create a pattern to test.
Using regular expressions can significantly decrease coding. To use regular
expressions, the following has to be done:

1. create a variable to test (in this case the phone number).


2. create the pattern to test against and assign it to a variable.

3. Test and then finally print out the result.

The pattern for the phone case is as follows:

var check = /^\({0,1}[0-9]{3}\){0,1}[ \-\.]{0,1}[0-9]{3}[ \-\.]{0,1}[0-9]


{4}$/;

The code for this method of validating phone numbers is as follows.

<html><head>
<script language="JavaScript">
function checkForm(formObj) {
return checkPhone(formObj.myField.value); }
function checkPhone(phone) {
var check = /^\({0,1}[0-9]{3}\){0,1}[ \-\.]{0,1}[0-9]{3}[
\-\.]{0,1}[0-9]{4}$/;
if (!check.test(phone)) {
window.alert("Provide a valid phone number.");
return false;

}
return true;
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return checkForm(this);">
Phone: <input type="text" name="myField"><br>
<input type="submit">
</form>
</body></html>

The expected output for an invalid number format will be as follows:


A very frequently used feature of a website is the password verification or
password selection. In the code that follows in the table below a eight
character password is being requested and compared with a confirm password
box.

<html>
<head>
<script language="JavaScript">
function checkForm(formObj) {
return Password(formObj.myPassword.value,
formObj.myConfirm.value);
}
function Password(password,confirm) {
if (password != confirm) {
window.alert("Passwords don’t match.");
return false;
}
if (password.length < 8) {
window.alert("Passwords must be 8 or more characters");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return checkForm(this);">
Enter Password: <input type="password"
name="myPassword"><br>
Confirm Password: <input type="password"
name="myConfirm"><br>
<input type="submit">
</form>
</body></html>

The output will look as follows if a wrong confirmation is given or not given.
Chapter 19. Browser Windows
To put a message in the status bar of the browser use the following code.

<html>
<head>
<script language="JavaScript">
window.status
</script>
</head>
<body>
<script language="JavaScript">
window.status = "A new status message";
</script>
</body>
</html>

We have used alert function of JavaScript in many of the script examples in


previous chapters. In addition to this as a dialog box there are other dialog
boxes. The code below brings up a confirmation dialog box.

<html>
<head>
</head>
<body>
<script language="JavaScript">
var userChoice = window.confirm("Click OK or Cancel");
if (userChoice) {
document.write("You chose OK");
} else {
document.write("You chose Cancel");
}
</script>
</body>
</html>

The output will look as follows:


The following code will bring up a pop up prompt box. In the example a name
is being requested. When given the name will be printed across the page.

<html>
<head>
</head>
<body>
<script language="JavaScript">
var userName = window.prompt("Please Enter Your
Name","Enter Your Name Here");
document.write("Your Name is " + userName);
</script>
</body>
</html>
To open a particular page in a browser use windows.open("url") within script
tags similar to the code below.

<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow");
</script>
</body>
</html>
The following code allows to control the height and width of the new browser
window that is opened to load a page.

<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","height=300,
width=500");
</script>
</body>
</html>

The following code allows to control the location where the new browser
window will open. The only additional code is the x and y coordinates and the
distance in pixels from the top.

<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","height=300,
width=500, screenx =600, screeny = 800, top= 300");
</script>
</body>
</html>

The following code allows the toolbars to be seen in the new window opened
to load a page. Setting toolbar = no will hide the toolbar of the browser.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","toolbar=yes");
</script>
</body>
</html>
The following code allows for the control of scroll bars in the new window
opened for a page.

<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","scrollbars=yes",
"height=300, width=300");
</script>
</body>
</html>

The following code allows for the new window opened to load a page to be
resizable.

<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","resizable=yes,
height=300, width=300");
</script>
</body>
</html>

Setting the value of resizable to no will make the page non expandable. A
window can be closed by using the window.close() feature of JavaScript. Add
this after the window.open statement above and see the result.
Chapter 20. Moving Objects
Objects have been mentioned and discussed in a previous chapter. Objects are
referenced in JavaScript by using the document.getElementById method. Each
object that needs to be used will require an ID using the id attribute of the
element’s tag.

In the following code, an object id is given to a function called space. A


variable val is associated with this id. In the body of the document create a
layer using <div> tag and the give it an id which in this case is myspace. The
code is as follows.

<html>
<head>
<script language="JavaScript">
function space(objectID) {
var val = document.getElementById(objectID);
val.style.lineHeight = parseInt(val.style.lineHeight) + 25 +
"px";
}
</script>
</head>
<body>
<div id="myspace"style="position: absolute; left: 100px;
top: 50px; width: 300px; font-size: 14px; line-height: 18px;
background-color: #cccccc;">Increasing line spacing for
this text. This is the second line. This is the third line. This
is the fourth line.</div>
<a href="javascript:space('myspace');">Increase line
spacing.</a>
</body>
</html>

The output of this code to increase space between the lines will look as
follows.
In the above code the line spacing will increase with each click of the link.
The link can also be made as a button.

In the following code the same technique as above to get the location of an
object. A function loc calls on an object and a variable val is used to reference
the object. Location details are obtained from val.style statement. The object of
interest is passed on to the function to get the results.

<html>
<head>
<script language="JavaScript">
function loc(objectID) {
var val = document.getElementById(objectID);
var x = val.style.left;
var y = val.style.top;
window.alert("Location: (" + x + "," + y + ")");
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:loc('myspace');">Where is the object?
</a>
</body>
</html>

The expected output is as follows.


The code above can be modified slightly to move the object of interest to a
particular coordinate in terms of pixels. The code still uses the style property
of the object. The code is as follows.

<html>
<head>
<script language="JavaScript">
function loc(objectID) {
var val = document.getElementById(objectID);
val.style.left = 500;
val.style.top = 200;
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:loc('myspace');">Move the object to
500,200 location</a>
</body>
</html>

The output after moving the object is as follows.

The X marks the location of the original text.

In the code above the object has moved both along x and y axis. If only
horizontal movement is required, then the statement val.style.top need not be
included. Similarly, if only vertical movement is only required then the
val.style.left statement need not be included.
It is possible to create buttons that call upon functions to move horizontally or
vertically.

The following code will keep the object in the horizontal center.

<html>
<head>
<script language="JavaScript">
function hz(objectID) {
var val = document.getElementById(objectID);
var width = document.body.clientWidth
var objectWidth = val.style.width;
var loc = (width - objectWidth) / 2;
val.style.left = loc;
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:hz('myspace');">Move the object to
horizontal center.</a>
</body>
</html>

The following code uses the document.body.clientWidth property to find the


width of the working area in pixels. It is applicable for IE and Google Chrome
browsers.

For Netscape the equivalent is window.innerWidth

An object can be kept vertically centered by using the same above code by
changing the var width to:

var height = document.body.clientHeight (for IE or Chrome browsers)


or var height = window.innerHeight for Netscape browsers.

The code will look like the one in the table below.

<html>
<head>
<script language="JavaScript">
function hz(objectID) {
var val = document.getElementById(objectID);
var height = document.body.clientHeight
var objectHeight = val.style.height;
var loc = (height - objectHeight) / 2;
val.style.top = loc;
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:hz('myspace');">Move the object to
vertical center.</a>
</body>
</html>

The follow code allows to hide an object. The structure of the code is similar
to the code written above in the chapter.

<html>
<head>
<script language="JavaScript">
function hz(objectID) {
var val = document.getElementById(objectID);
val.style.visibility="hidden";
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:hz('myspace');">Hiding an object.</a>
</body>
</html>

The object will now be hidden on clicking the link. The key term above is the
style.visibility statement . If it is set to hidden the object will not be visible.
The opposite is visible.

The following code will give color depth of the monitor being used to observe
the result of code.

<html>
<head>
<script language="JavaScript">
var depth = window.screen.colorDepth;
var colors = Math.pow(2,depth);
document.write(depth + "bits which means" + colors +
"colors");
</script>
</head>
<body>
</body>
</html>

Here the depth will give an answer in bits and colors will be 2 ^depth. The
result will be as follows.

The value varies with the monitor.


A point to note in all the chapters is that there are four ways in general to
output something in JavaScript.

The document.write method

The document.getElementByid(id) which has been used in the last two chapters
in particular with objects.

window.alert or alert which has been used as an alert box.

The console.log used for debugging purposes. This has not been used in this
book but do not stop from using if appropriate.
Appendix I. Creating a simple drop down menu
No book on JavaScript can be complete without bringing up the subject of
menus. There are many ways menus can be designed. They can be designed
completely without JavaScript. To use JavaScript however the most common
way is to use three parts to the code.

The first part in the header is the cascading style sheet. This (css) is a separate
subject in itself. It can be either external in a text file or inline as in the
examples shown here.

The second part is the JavaScript which will do the functions of opening the
menu and letting users scroll and select.

The third part is the html script in the body of the web page. As mentioned
before a good knowledge of html and css is required to fully utilize JavaScript.
Let us take the following style sheet details.

<html>
<head>
<style>
#f1
{ margin: 0;
padding: 0;
z-index: 30}

#f1 li
{ margin: 0;
padding: 0;
list-style: none;
float: left;
font: bold 11px arial}

#f1 li a
{ display: block;
margin: 0 1px 0 0;
padding: 4px 10px;
width: 60px;
background: #5970B2;
color: #FFF;

text-align: center;
text-decoration: none}

#f1 li a:hover
{ background: #49A3FF}

#f1 div
{ position: absolute;
visibility: hidden;
margin: 0;
padding: 0;
background: #EAEBD8;
border: 1px solid #5970B2}

#f1 div a
{ position: relative;
display: block;
margin: 0;
padding: 5px 10px;
width: auto;
white-space: nowrap;
text-align: left;
text-decoration: none;
background: #cccccc;
color: #2875DE;
font: 11px arial}

#f1 div a:hover


{ background: #49A3FF;
color: #FFF}
</style>

The style sheet will give the colors, backgrounds and sizes of a menu and its
drop down elements. Only one part of the menu is being shown. One can repeat
the same process to develop a larger menu.

The menu shown here will show the word “Home” and when the mouse is
placed over it the drop down links will be Link one, Link two, Link three
respectively.

Now let us look at the JavaScript part of the code.


<script>
var ftime = 100;
var ctime = 0;
var val = 0;
function openmenu(id)
{
menucanceltime();
if(val) val.style.visibility = 'hidden';
val = document.getElementById(id);
val.style.visibility = 'visible';
}
function menuclose()
{
if(val) val.style.visibility = 'hidden';
}
function menuclosetime()
{
ctime = window.setftime(mclose, ftime);
}
function menucanceltime()
{
if(ctime)
{
window.clearftime(ctime);
ctime = null;
}
}
document.onclick = menuclose;
</script>
The script calls a function openmenu to which an object is being passed. The
visibility of that object depends upon whether the mouse is over the menu or
not. When the menu closes the visibility of the object also ends.

The next part of the code is that related to the body of the web page. The body
in this case includes a <div> statement similar to the ones in the chapter on
moving objects.

The code starts with identifying the element in the style or cascading sheet
code that will give the shape of the page. This is given by the id = f1 line. Thus
the style of the page will be set from the details provided in the style sheet.
Any style sheet can be used and the design of the style sheet will not affect the
JavaScript code above.
The code for the body of the web page is as follows.

<body>
<ul id="f1">
<li><a href="#"
onmouseover="openmenu('m1')"
onmouseout="menuclosetime()">Home</a>
<div id="m1"
onmouseover="menucanceltime()"
onmouseout="menuclosetime()">
<a href="#">Link one</a>
<a href="#">Link two</a>
<a href="#">Link three</a>
</div>
</li>
</ul>
<div style="clear:both"></div>
</body>
</html>

The output is as follows.


By adding appropriate references to < a href > the user can see different pages
upon clicking links one, two and three.

The id of the next menu if the user wants to create it will be m2 and so on.
Appendix II. References
I compiled this book for a web page development class at the undergraduate
level.

The following sources were referred to for making this book:

JavaScript, Arman Danesh, Wiley Publishing, 2004

Programming JavaScript Applications, Erric Elliott, OReilly, 2014 First


Edition

JavaScript Definitive Guide, David Flanagan, OReilly, 6th Edition, 2011

Learning JavaScript, Shelley Powers, OReilly, 2nd Edition, 2008

Computer code was referred from the following sources and modified as
needed for the chapters:

https://www.w3schools.com

https://docs.microsoft.com/en-us/scripting/javascript/writing-javascript-code

https://developer.mozilla.org

You might also like