0% found this document useful (0 votes)
2 views33 pages

JavaScript Final Notes Updated

Uploaded by

jachsnydar767
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)
2 views33 pages

JavaScript Final Notes Updated

Uploaded by

jachsnydar767
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/ 33

JavaScript

Javascript is a dynamic computer programming language. It is lightweight and most


commonly used as a part of web pages, whose implementations allow client-side
script to interact with the user and make dynamic pages. It is an interpreted
programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because
of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995
with the name LiveScript. The general-purpose core of the language has been embedded in Netscape,
Internet Explorer, and other web browsers.

Javascript can be thought of as an extension to HTML which allows authors to incorporate some
functionality in their web pages. So now, whenever the user presses the SUBMIT button, you
don't necessarily have to invoke a Common Gateway Interface (cgi) script to do the processing.
If it is something simple, you can do the processing locally using Javascript and give back the
results. Javascript can also be used in a number of ways to spice up your page.

JavaScript:
• was designed to add interactivity to HTML pages
• is a scripting language.
• is a lightweight programming language.
• is usually embedded directly into HTML pages.
• is an interpreted language (means that scripts execute without preliminary compilation).
• can be used by everyone without purchasing a license.

What JavaScript can do


• JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
• JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser.
• JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer.
Advantages of JavaScript
The merits of using JavaScript are:
• Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors: They don't have to wait for a page reload to see if
they have forgotten to enter something.
• Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
• Richer interfaces: You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

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

JavaScript Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it is
normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes:
• Language: This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.

• Type: This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".

So your JavaScript syntax will look as follows.


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

Syntax Rules
• Statements may contain a semicolon at the end of them as in C, but it is not necessary
unless there are multiple statements on one line. Multiple statements on one line must be
separated by a semicolon.
• JavaScript is case sensitive.
• Quotes may be single quote (') or double quote ("). When embedded within each other
they must be used consistently as in the following example.

onMouseOver="window.status='To Operating Systems Section' ;return true"

• Comments are the same as in C++ with the "//" characters for a single line comment, and
the "/*" for the beginning of a multiline comment and the "*/" for the end of a multiline
comment.
• Variables must be defined before they are used.

JavaScript Code

Let us take a sample example to print out "Hello World". We added an optional HTML comment
that surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we
add that to prevent a browser from reading the end of the HTML comment as a piece of
JavaScript code. Next, we call a function document.write which writes a string into our HTML
document.

This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Welcome to JavaScript!")
//-->
</script>
</body>
</html>

This code will produce the following result:

Welcome to JavaScript!
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
• Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.

• Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.

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

JavaScript Placement
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows:
• Script in <head>...</head> section.

• Script in <body>...</body> section.

• Script in <body>...</body> and <head>...</head> sections.

• Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can place JavaScript in an HTML file in different
ways.
1. JavaScript in <head>...</head> Section
If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>
</html>
This code will produce the following results:

Click here for the result

Hello World

2. JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This code will produce the following result.
Hello World

Say Hello

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


If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This code will produce the following results:

Hello World

4. JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This code will produce the following result.
HelloWorld

Say Hello

5. JavaScript in External File


As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it into
your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source code
in a simple text file with the extension ".js" and then include that file as shown above.

For example, you can keep the following content in filename.js file and then you can use
sayHello function in your HTML file after including the filename.js file.

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

JavaScript Variables

Variables are "containers" for storing information.


JavaScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for JavaScript variable names:
• Variable names are case sensitive (y and Y are two different variables)
• Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
Like many other programming languages, JavaScript has variables. Variables can be thought of as named
containers. You can place data into these containers and then refer to the data simply by naming the
container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the
var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time
of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Example
A variable's value can change during the execution of a script. You can refer to a variable by its
name to
display or change its value.
<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>
<p>The script above declares a variable,
assigns a value to it, displays the value, change the value,
and displays the value again.</p>
</body>
</html>
Output :
Welcome
XYZ
Variable Scope
The scope of a variable is the region of your program in which it is defined.
JavaScript variables have only two scopes.
Global Variables: A global variable has global scope which means it can be
defined anywhere in your JavaScript code.

Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global
variable with the same name. If you declare a local variable or function parameter
with the same name as a global variable, you effectively hide the global variable.
Take a look into the following example.
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
It will produce the following result:

Local

DataTypes
• Numbers - are values that can be processed and calculated. You don't enclose them in
quotation marks. The numbers can be either positive or negative.
• Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses
the string literally; it doesn't process it. You'll use strings for text you want displayed or
values you want passed along.
• Boolean (true/false) - lets you evaluate whether a condition meets or does not meet
specified criteria.
• Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,
whereas null is the absence of any value.

JavaScript Reserved Words


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

abstract else Instanceof switch


boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
JavaScript Operators
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is
called the operator. JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Let’s have a look at all the operators one by one..

Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
–– Decrement
- Negation

Strings are concatenated together using the "+" operator.

Bitwise Operators
These operators work at the bit level performing the operator function on a bit per bit basis. The
operation must be thought of as binary, octal, or hexadecimal values (depending on preference)
to consider how it works. Consider the decimal number 15.

15 & 3 = 3 - Equivalent binary: 1111 & 0011 = 0011


15 | 3 = 15 - Equivalent binary: 1111 | 0011 = 1111
15 | 16 = 31 - Equivalent binary: 1111 | 10000 = 11111
15 | 30 = 31 - Equivalent binary: 1111 | 11110 = 11111
Operator Meaning
& AND
~ NOT
| OR
^ exclusive OR
<< Left shift
>> Right shift
>>> Right shift, fill with zeros

Logical Operators
Logical operators operate on boolean values which are either true or false.

Operator Meaning
&& AND
|| OR
! NOT
? Conditional
, Comma

• The syntax for the conditional operator is:


• condition ? ActionIfTrue : ActionIfFalse

JavaScript Control Statements


This page descibes the use of JaveScript control statements such as the if statement, while
statement, the for statement, and the switch statement. It provides examples.

if
if (value == 3)
{
document.write("Value is three")
}
else
{
document.write("Value is not three")
}
While
var i = 0
while (i < 3)
{
i++
}

Do While

The example prints the days of the week.

days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var day = 0
do
{
document.write(days[day] + " is day " + eval(day+1) + " of the
week.<BR>\n")
day++
} while (day < 7)

For

The following example will determine what numeric day of the week Wednesday falls on.

days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturda
y")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i])
{
place = i + 1
}
}
document.write(day + " is day " + place + " in the week.<BR>\n")

The switch statement

Runs one or more commands based on the value of the expression being evaluated. An
example is:

switch (day) {
case 1:
document.write("Sunday<BR>\n")
break
case 2:
document.write("Monday<BR>\n")
break
case 3:
document.write("Tuesday<BR>\n")
break
case 4:
document.write("Wednesday<BR>\n")
break
case 5:
document.write("Thursday<BR>\n")
break
case 6:
document.write("Friday<BR>\n")
break
case 7:
document.write("Saturday<BR>\n")
break
default:
document.write("Invalid Weekday<BR>\n")
break
}

Break

The break statement may be used to break out of a while, if, switch, dowhile, or for
statement. The break causes program control to fall to the statement following the iterative
statement. The break statement now supports a label which allows the specification of a
location for the program control to jump to. The following code will print "Wednesday is day
4 in the week".

days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturda
y")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i]) break;
}
place = i + 1
document.write(day + " is day " + place + " in the week.<BR>\n")

Continue

The continue statement does not terminate the loop statement, but allows statements below
the continue statement to be skipped, while the control remains with the looping statement.
The loop is not exited. The example below does not include any ratings values below 5.

ratings = new Array(6,9,8,4,5,7,8,10)


var sum = 0;
var reviews = 0
for (i=0; i < ratings.length; i++)
{
if (ratings[i] < 5) continue
sum += ratings[i];
reviews++;
}
var average = sum/reviews

For in Statement

Executes a loop similar to a for statement that executes for all the properties in an object. The
example below lists all properties and their values for the document object. The document is
the HTML page being displayed.

for (i in document)
{
document.write("Property = " + i + " Value = " + document[i] +
"<BR>\n")
}

A few of the properties and their values are:

Property = activeElement Value = [object]


Property = alinkColor Value = #ff0000
Property = all Value = [object]
Property = anchors Value = [object]
Property = applets Value = [object]
Property = bgColor Value = #ffffff
Property = body Value = [object]
Property = cookie Value = pageCount=9
Property = defaultCharset Value = iso-8859-1
Property = domain Value =
Property = embeds Value = [object]
Property = fgColor Value = #000000
Property = fileCreatedDate Value = Thursday, September 21, 2000
.
.

With Statement

Eliminates references to the object within the statement by identifying the default object to be
used inside the braces. This example prints out the document properties and values without
referencing the document object to perform the function.

with (document)
{
for (i in this)
{
write("Property = " + i + " Value = " + document[i] + "<BR>\n")
}
}

Defining Functions
Javascript functions are defined using the key word "function" followed by its name and
variables being passed to it in the following syntax:

function fname(value1,value2, ...)


{
statement1
statement2
.
}

An example:

<HTML>
<HEAD>
<TITLE>A function definition</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hiding JavaScript
function listItems(itemList)
{
document.write("<UL>\n")
for (i = 0;i < itemList.length;i++)
{
document.write("<LI>" + itemList[i] + "\n")
}
document.write("</UL>\n")
}
// End hiding JavaScript -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
listItems(days)
// -->
</SCRIPT>
</BODY>
</HTML>

Calling Functions

If evaluate() is a defined function, the following line will call the function:

<SCRIPT LANGUAGE="JavaScript">
<!--
i3 = evaluate (Tree)
// -->
</SCRIPT>

This function may evaluate the members of the array tree to see how many match a certain
criteria.
Another way to call a function is to tie it to an anchor:

<A HREF="javascript:redirectLink()">redirecting</A>

Another way is to tie it to an event:

<A NAME="javatest" onClick="redirectLink()">redirecting</A>

This will cause the redirectLink() function to run when the text "redirecting" is clicked on. The
text inside the anchor reference is not marked as a link, nor does the mouse change when placed
over the text. This is one way to make truly invisible links, that no one would know had any
function until they click on it.

Functions Properties

Functions in JavaScript is actually an object. Therefore any created function created using the
"function" declaration will have the properties of a function. These properties are:

• arguments - An array of arguments passed to the function. This is an array object which
has a property of length which enables the programmer to tell how many arguments (or
variables)are passed to the function.
• caller - The name of the function that called the function.
• prototype - Used to make more properties.

Using the Arguments Array

The arguments array is a member of every function. It can be used to determine how many
variables are being passed to the function, and what they are, without each argument being
explicitly declared in the function. The following example performs the same task as the above
example:

function listItems()
{
var items = listItems.arguments.length
document.write("<UL>\n")
for (i = 0;i < items;i++)
{
document.write("<LI>" + listItems.arguments[i] + "\n")
}
document.write("</UL>\n")
}

The function may be called as follows:

listItems("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturd
ay","Happyday")

Local variables
Local variables may be defined inside functions. The following example uses the variables, sum
and items as local variables.

function average()
{
var items = average.arguments.length
var sum = 0
for (i = 0; i < items;i++)
{
sum += average.arguments[i]
}
return (sum/items)
}
document.write(average(6,9,8,4,5,7,8,10))

Return

As in the example above, the return statement will return a value to the statement that invoked
the function. In the above example, the average value is written to the document. The return
statement will return the value as float, string, integer or whatever is appropriate for use.

JavaScript Predefined Functions


This page discusses JavaScript predefined functions such as escape, unescape, eval, isNaN,
tostring, alert, and others.

Conversion and Comparison

• escape(string) - Encodes a string from ASCII into an ISO Latin-1 (ISO 8859-1) character
set which is suitable for HTML processing. It is passed the string to be encoded, and
returns the encoded string.
• unescape - Converts an ISO8859-1 character set to ASCII.

If a string is "My phone # is 123-456-7890", after the escape function, it is


"My%20phone%20%23%20is%20123-456-7890". After unescape, it is "My phone # is
123-456-7890".

• eval()- Converts a string to integer or float value. It can also evaluate expressions
included with a string. In the example, value1 becomes 62.

value1 = eval("124/2") ,

• isNaN(value) - If the value passed is a not a number, the boolean value of true is
returned, if it is a number, it returns false.

if (isNaN(string1))
{
document.write("String1 is not a number\n");
}
else
{
document.write(String1 is a number\n");
}

• parseFloat() - Returns floating point numbers the same as the parseInt function, but looks
for floating point qualified strings and returns their value as a float. The first line below
returns a value of 123, and the second line returns 9.683.

value1 = parseFloat("123")
value2 = parseFloat("9.683")

• parseInt()- Converts a string to an integer returning the first integer encountered which is
contained in the string. In the example, value1 becomes 12.

value1 = parseInt("12b13") ,

If no integer value were found such as in the string "abcd", then a value of 0 is returned.

• typeof operator - This is an operator but its usefullness is similar to a function. This
operator returns the type of the object it operates on. Values returned are string values
and may be one of "undefined", "object", "function", "number", "Boolean", or "string".
The example will return the string "number".

typeof 10

• taint
• untaint(element) -

valueOf()

Methods that belong to all objects

• toString() - Converts an object to a string. The syntax is shown below. Radix is the base
value for the conversion, which may be 10 for decimal conversion. The value 1 is used
for binary conversion, and 8 is used for octal conversion.

object.tostring(radix)

Dialog Boxes

• alert(message) - Displays an alert box with a message defined by the string message.
Example:

alert("An error occurred!")


• confirm(message) - When called, it will display the message and two boxes. One box is
"OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a
value of false is returned. An example:

if (confirm("Select OK to continue, Cancel to abort"))


{
document.write("Continuing")
}
else
{
document.write("Operation Canceled")
}

• prompt(message) - Displays a box with the message passed to the function displayed. The
user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses
Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the
field is returned. An example:

var response=prompt("Enter your name")


if (response != null)
{
document.write(response)
}

JavaScript Events
JavaScript Events are items that transpire based on an action. A document event is the loading of
an HTML document. A form event is the clicking on a button. Events are objects with properties.

Event Properties

• x -Mouse x coordinate when the event happened.


• y -Mouse y coordinate when the event happened.

JavaScript defines five types of events which are form, image, image map, link, and window
events. Events are associated with HTML tags. The definitions of the events described below are
as follows:

Form Events

• blur - The input focus was lost.


• change - An element lost the focus since it was changed.
• focus - The input focus was obtained.
• reset - The user reset the object, usually a form.
• select - Some text is selected
• submit - The user submitted an object, usually a form.
Image Events

• abort - A user action caused an abort.


• error - An error occurred.
• load - The object was loaded.

Image Map Events

• mouseOut - The mouse is moved from on top a link.


• mouseOver - The mouse is moved over a link.

Link Events

• click - An object was clicked.


• mouseOut - The mouse is moved from on top a link.
• mouseOver - The mouse is moved over a link.

Window Events

• blur - The input focus was lost.


• error - An error occurred.
• focus - The input focus was obtained.
• load - The object was loaded.

unload - The object was exited.

Event Association

Events are associated with HTML tags. The definitions of the events described below are as
follows:

• abort - A user action caused an abort of an image or document load.


• blur - A frame set, document, or form object such as a text field loses the focus for input.
• click - Happens when a link or image map is clicked on
• change - Happens when a form field is changed by the user and it loses the focus.
• error - An error happened loading a image or document.
• focus - A frame set, document, or form object such as a text field gets the focus for input.
• load - The event happens when an image or HTML page has completed the load process in the
browser.
• mouseOut - The event happens when the mouse is moved from on top of a link or image map
• mouseOver - The event happens when the mouse is placed on a link or image map.
• reset - The user reset the object which is usually a form.
• submit - The user submitted an object which is usually a form.
• unload - The object such as a framesed or HTML document was exited by the user.
The events for each HTML tag are as follows:

• <A>
o click (onClick)
o mouseOver (onMouseOver)
o mouseOut (onMouseOut)
• <AREA>
omouseOver (onMouseOver)
omouseOut (onMouseOut)
• <BODY>
o blur (onBlur)
o error (onError)
o focus (onFocus)
o load (onLoad)
o unload (onUnload)
• <FORM>
o submit (onSubmit)
o reset (onReset
• <FRAME>
o blur (onBlur)
o focus (onFocus)
• <FRAMESET>
o blur (onBlur)
o error (onError)
o focus (onFocus)
o load (onLoad)
o unload (onUnload)
• <IMG>
o abort (onAbort)
o error (onError)
o load (onLoad)
• <INPUT TYPE = "button">
o click (onClick)
• <INPUT TYPE = "checkbox">
o click (onClick)
• <INPUT TYPE = "reset">
o click (onClick)
• <INPUT TYPE = "submit">
o click (onClick)
• <INPUT TYPE = "text">
o blur (onBlur)
o focus (onFocus)
o change (onChange)
o select (onSelect)
• <SELECT>
o blur (onBlur)
o focus (onFocus)
o change (onChange)
• <TEXTAREA>
o blur (onBlur)
o focus (onFocus)
o change (onChange)
o select (onSelect)

Event Handlers

Event handlers are created as follows:

onEvent = "Code to handle the event"

The following example demonstrates its use:

<a href="independent/index.html" target="_top" onMouseOver="window.status='To


Independent Technologies Section' ;return true" onMouseOut="window.status='';return
true"><img SRC="gifs/greenindependentbutton2.gif" ALT="Independent Technologies"
VSPACE=3 BORDER=0 height=35 width=120></a><BR>

As you can see, the event handling attribute is included in the HTML tag. When multiple
statements are included in the event handling code, the statements are separated by a semicolon.

The following example can be used to redirect a link to another location:

<HTML>
<HEAD>
<TITLE>Using functions as event handlers</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function nameDefined(ckie,nme)
{
var splitValues
var i
for (i=0;i<ckie.length;++i)
{
splitValues=ckie[i].split("=")
if (splitValues[0]==nme) return true
}
return false
}
function delBlanks(strng)
{
var result=""
var i
var chrn
for (i=0;i<strng.length;++i) {
chrn=strng.charAt(i)
if (chrn!=" ") result += chrn
}
return result
}
function getCookieValue(ckie,nme)
{
var splitValues
var i
for(i=0;i<ckie.length;++i) {
splitValues=ckie[i].split("=")
if(splitValues[0]==nme) return splitValues[1]
}
return ""
}
function testCookie(cname, cvalue) { //Tests to see if the cookie
var cookie=document.cookie //with the name and value
var chkdCookie=delBlanks(cookie) //are on the client computer
var nvpair=chkdCookie.split(";")
if(nameDefined(nvpair,cname)) //See if the name is in any pair
{
tvalue=getCookieValue(nvpair,cname) //Gets the value of the cookie
if (tvalue == cvalue) return true
else return false
}
else return false
}
function redirectLink() {
if (testCookie("javahere", "yes")) {
window.location="javahere.html"
}
else{
var futdate = new Date()
var expdate = futdate.getTime()
expdate += 3600*1000 //expires in 1 hour(milliseconds)
futdate.setTime(expdate)
var newCookie="javahere=yes; path=/;"
newCookie += " expires=" + futdate.toGMTString()
window.document.cookie=newCookie
window.location="javanot.html"
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Using an event handler to direct a link based on a cookie value</H3>
<P>
<A NAME="Here" onClick="return redirectLink()">See if you've been here.</A>
</P>
</BODY>
</HTML>

Using an event handler to direct a link based on a cookie value

Exercises
Changing Background Color
Javascript makes it possible to change background color of a document dynamically. This means that
you can have terrible visual effects like the one you just saw. Actually, I had planned to make a smooth
shade out sort of thing but somehow, it got like this.

Your turn now. Select your favorite color from here :

The command for changing the background color is


document.bgColor = "rrggbb"
where "rrggbb" is a string specifying the red, green and blue components of the color in hexadecimal.
The code for the above example is given below.
<FORM>
<SELECT onChange=
"document.bgColor=this.options[this.selectedIndex].value">
<OPTION VALUE="40E0D0"> Torquoise
<OPTION VALUE="2E8B57"> Sea Green
<OPTION VALUE="87CEEB"> Sky Blue
<OPTION VALUE="F4A460"> Sandy Brown
<OPTION VALUE="FFF0F5"> Lavender Blush
<OPTION VALUE="FF1493"> Deep Pink
<OPTION VALUE="FFFFFF" SELECTED> White
</SELECT>
</FORM>

If you specify a background image, then background color will have no effect. So on pages like these, it's
better not to specify a background image.

Programming the Scroller

A scroller is text which scrolls on the status bar of the browser. Take a look at your status bar to
see my scroller. Scrollers are very popular with JavaScript authors (esp. newbies like ourselves)
and equally unpopular with the rest of the Web community

How much programming does it take to create a scroller? Twenty lines, to be exact, as you will
see. But before we go into the code, let us understand what features of JavaScript makes the
scroller possible.

First is the ability to write to the status bar using the window.status property like this:
window.status = "This will appear in the status bar"

The second is the setTimeout() function. This function takes two parameters. The first is a string
specifying the JavaScript statement to be executed on triggering and the second is a number
specifing time in milliseconds after which triggering occurs.

Our scroller is essentially a function which, on each invocation, moves the text on the scroll bar a
little to the left and then calls setTimeout() to invoke itself after a small interval of time.

Here is the complete code for the scroller.


<SCRIPT LANGUAGE="JavaScript">
<!-- Start of scroller script
var scrollCounter = 0;
var scrollText = "Any text here";
var scrollDelay = 70;
var i = 0;

while (i ++ < 140)


scrollText = " " + scrollText;

function Scroller()
{
window.status = scrollText.substring(scrollCounter++,
scrollText.length);
if (scrollCounter == scrollText.length)
scrollCounter = 0;
setTimeout("Scroller()", scrollDelay);
}

Scroller();
// End of scroller script -->
</SCRIPT>
The only other function we use is substring() which is a method of the string object. If
name="JavaScript", then name.substring(4,9) will return "Script". You get the general idea,
right?

Getting the Scroller on your page

If programming is not one of your strong points, you can still have the scroller on your page. Just
copy the above code into your HTML file, preferably between <HEAD> and </HEAD> tags and
change the scrollText and scrollDelay variables in lines 4 & 5 to suit yourself.

Date and Time functions


To make it easy to handle date and time, JavaScript has a built in Date object. A Date variable
has to be created explicitly before we can use it. This can be done using the following JavaScript
statement.

dateVar = new Date();

This creates a variable called dateVar and initializes it to contain the curent date and time. If you
want to initialize it with some other date and time, you can use any of the following alternate
syntaxes.

dateVar = new Date("month day, year hours:minutes:seconds")


dateVar = new Date(year, month, day)
dateVar = new Date(year, month, day, hours, minutes, seconds)

Methods of the Date Object


The most commonly used methods of Date are given below.
getYear()
dateVar.getYear() returns a number like 96 corresponding to the year of dateVar.
getMonth()
Returns a number between 0 and 11 corresponding to months January to December.
getDate()
Returns the day of the month.
getDay()
Returns a number specifying the day of the week. Zero is for Sunday, one for Monday
and so on.
getHours()
Returns a number between 0 and 23 specifying the hour of day.

You might have come across sites that wish you a Good morning or a Good evening depending
on the time you visit it. This can b e achieved by checking the current time and inserting the
appropriate greeting using the document.write() function. The following code does just that.
You can insert it into an HTML file at the point you wish the greeting to appear.

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this code from non JavaScript browsers
currentTime = new Date();
if (currentTime.getHours() < 12)
document.write("Good morning");
else if (currentTime.getHours() < 17)
document.write("Good afternoon");
else document.write("Good evening");

// End of JavaScript code -->


</SCRIPT>

A Digital Clock

Here is a clock program written in JavaScript.

The source code for it is given below.

<TABLE BORDER=4 BGCOLOR=CYAN>


<TR><TD>
<FORM NAME="clock_form">
<INPUT TYPE=TEXT NAME="clock" SIZE=26>
</FORM>

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from non JavaScript browsers
function clockTick()
{
currentTime = new Date();
document.clock_form.clock.value = " "+currentTime;
document.clock_form.clock.blur();
setTimeout("clockTick()", 1000);
}
clockTick();
// End of clock -->
</SCRIPT>
</TD></TR>
</TABLE>

The setTimeout() function is discussed in more detail on the Scroller page. The blur()
method is used to remove focus from the Clock textbox.

Showing the new Item Icon


When you add something to your site or modify something, you usually place a icon next to
it so that visitors can easily find it. The idea is to display the icon for a fixed period of time and
then remove it. However, if you are constantly modifying your site or if you have a large number
of pages, then keeping track of all the new icons becomes very difficult.

Using JavaScript, it is possible to program your HTML to display the new icon only for a certain
period of time. You write a JavaScript function which compares the current date with the expiry
date and inserts the new icon only if the current date has not exceded the expiry date. Here is the
code :

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function newItem(expiryDate)
{
exp = new Date(expiryDate);
cur = new Date();
if (cur.getTime() < exp.getTime())
document.write("<IMG SRC=\"new.gif\" WIDTH=31
HEIGHT=12 BORDER=0 ALT=\"new\">" );
}
// end hiding -->
</SCRIPT>
Usually, functions like this are defined between the <HEAD> and </HEAD> part of the HTML.
Change the new.gif to the name of your image and modify the WIDTH and HEIGHT attributes
accordingly. Now where ever you wan to put the icon, insert the following code :
<SCRIPT LANGUAGE="JavaScript">
<!--
newItem("10/1/96");
// -->
</SCRIPT>

The icon will be shown up to the date you specify as the parameter for newItem().

Opening and Manipulating Windows


If you have ever been near any of the homepages in Geocities or Tripod, you must be familiar
with the small window that pops up with an advertisement banner. Undoubtedly, you considered
it irritating and in bad taste. But believe me when I say that it is much more fun when you do the
popping up yourself. Not convinced...? Click here now!

I am not giving the source code for that because you're better off not doing that to your visitors ;-

Pop-up windows are usually used when you want to display something to the users but you don't
want them to leave the page that they are currently viewing (Perhaps you are afraid that they
might not return). How about a Trivia Game as our next sample. I recently came across this
game and found it very entertaining. You are asked ten questions rapid-fire style, the faster you
answer, the more points you get. If you get more than 1500 points, you qualify for the $25
weekly drawing by registering. So, if you are ready to play, click here.
Note: If you qualify, you might want to maximize the game window to register.

Let us now look at the code used to create that link.

<A HREF="" onClick="window.open('trivia.html', 'triviaWnd',


'width=370,height=240,status=1'); return false;">click here</A>
Note that I am using single quote for nested strings. The 'return false' part tells the
browser that when the user clicks on the link, the browser should stay on the same page rather
than load the page specified by HREF. The onClick() handler calls the window.open() function
to open a new browser window. The first parameter, 'trivia.html' is the URL of the file to
load in the new window. So our window displays trivia.html when it opens. (Note that it doesn't
have to be an HTML file. It could also be an image file or anything the browser can display.)
The second parameter, 'triviaWnd' is the name we wish to give to the new window. Details
about this later. The third parameter determines the dimensions and appearance of the window.
We have specified a window of size 370x240 and a status bar. Note that it is a comma-seperated
list. The apperance of the window can be controlled by changing the value of the third parameter.
The commonly used options are:
height
Height of the new window in pixels (eg: height=100)
width
Width of the new window in pixels (eg: width=200)
directories
Specifies whether to display the browser directory buttons like "What's Cool" etc. (eg:
directories=yes)
hotkeys
Enables or disables various hotkeys (eg: hotkeys=no)
location
Specifies whether the "Location" box is to be displayed (eg: location=yes)
menubar
Specifies whether the new window should have a menu bar (eg: menubar=yes)
resizable
Specifies whether the user is allowed to resize the new window (eg: resizable=no)
scrollbars
Specifies whether the new window can have scroll bars if necessary (eg:
scrollbars=yes)
toolbar
Specifies whether the new window has a toolbar (eg: toolbar=yes)

Instead of yes/no values, you may also give 1/0. i.e., you may write toolbar=1 instead of
toolbar=yes.

Here are some combinations that you can try for yourself. All of them open this document in a
new window with different functionalities.

<A HREF="" onClick="window.open('windows.html', 'newWnd',


'width=500,height=400'); return false;">Try this</A>
Try this
A basic window. No menu, no toolbar, no status bar, not even scroll bars.
<A HREF="" onClick="window.open('windows.html', 'newWnd',
'width=500,height=400,menubar=yes,location=yes,scrollbars=yes');
return false;">Try this</A>
Try this
A window with menubar, location box and scroll bars.
<A HREF="" onClick="window.open('windows.html', 'newWnd',
'width=500,height=400,toolbar=1,status=1,scrollbars=1,resizable=1');
return false;">Try this</A>
Try this
A window with toolbar, statusbar and scroll bars. You can resize this window if you want which
wasn't possible with the other windows.

In the above code samples, I have split the code to multiple lines for easier reading but when you
use them, make sure that everything between the double quotes is on a single line.

Working with Forms


A Form is an HTML construct used to get input from the user, which is usually processed using
CGI Scripts or similar mechanisms.

Creating a form

The following is a form with three fields, a submit button and a reset button.

Enter your name :

Enter your age :

Date of birth :
The above form was created using HTML code similar to the following :
<FORM NAME="sample" METHOD=POST
ACTION="/cgi-bin/homestead/mail.pl?member_name">
Enter your name : <INPUT TYPE=TEXT NAME="yourname" SIZE=30><BR>
Enter your age : <INPUT TYPE=TEXT NAME="yourage" SIZE=3><BR>
Date of birth : <INPUT TYPE=TEXT NAME="yourdob" SIZE=10><BR>
<INPUT TYPE=SUBMIT> <INPUT TYPE=RESET>
</FORM>
We can refer to this form as document.sample since we have named the form as 'sample'. The
first text field is document.sample.yourname and the second field is
document.sample.yourage. To get the text which is entered in the first text field, you can use
document.sample.yourname.value. Now let us see how to go about validating the data
entered.

Validating the form

To add validation to your form, there are two things that have to be done. The first is to write a
JavaScript routine which does the validation (for this example, we will name the function
validateForm()) and the second is to modify the <FORM> tag to <FORM NAME="sample"
METHOD=POST ACTION="..." onSubmit="return validateForm()"> The above line tells the
browser to call validateForm() when the user submits the form. The following is the code for
validateForm()
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function validateForm1()
{
formObj = document.sample;
if ((formObj.yourname.value == "") ||
(formObj.yourage.value == "") ||
(formObj.yourdob.value == ""))
{
alert("You have not filled in all the fields.");
return false;
}
else
return true;
}
// end hiding -->
</SCRIPT>
And here is the form with the added validation.

Enter your name :

Enter your age :

Date of birth :
If any of the fields are blank, an alert box will pop up and the form won't be submitted. The form
is submitted if the validation routine returns a true; if it returns false, the submit operation is
cancelled.

Setting the focus


Note: The following example may not work on Microsoft Internet Explorer 3.x. You will find that the focus is not set properly. If anyone figures
out what the problem actually is, please let me know.

In the preceeding example, the message gave no clue as to which field is actually causing
problems. Usually forms are much bigger and such a message will not be of much use. In the
next form, not only is the message more informative, but the cursor is also placed at the erring
field so that the user can start typing in directly. For example, to position the cursor in the first
field (yourname), we can use the JavaScript function document.sample.yourname.focus().
Here is the modified function.

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function validateForm()
{
formObj = document.sample;
if (formObj.yourname.value == "")
{
alert("You have not filled in the name field.");
formObj.yourname.focus();
return false;
}
else if (formObj.yourage.value == "")
{
alert("You have not filled in the age field.");
formObj.yourage.focus();
return false;
}
else if (formObj.yourdob.value == "")
{
alert("You have not filled in your date of birth.");
formObj.yourdob.focus();
return false;
}
}
// end hiding -->
</SCRIPT>
Here is our new form.

Enter your name :

Enter your age :

Date of birth :
Manipulating Images
One of the more interesting things that you can do with JavaScript is playing around with images. To do
this you will need Netscape 3.0+ or IE4.0+.

The folowing example demonstrates how you can change an image dynamically after the page
has finished loading. I use the following two images to do the pseudo-animation.

fanoff.gif fan.gif

When you click on the "On" button, 'fan.gif' is displayed. When you click "Off", 'fanoff.gif' is
displayed. Note that I am only changing the images. The animation happens because 'fan.gif' is
an animated GIF.

Take a look at the JavaScript code needed to accomplish this:

<FORM>
<IMG NAME="coolfan" SRC="fanoff.gif"
WIDTH=61 HEIGHT=72><BR><BR>
<INPUT TYPE=BUTTON VALUE=" Off "
onClick="coolfan.src = 'fanoff.gif'">
<INPUT TYPE=BUTTON VALUE=" On "
onClick="coolfan.src = 'fan.gif'">
</FORM>

In the <IMG> tag, the NAME="coolfan" part is added so that we can refer to this image as
coolfan from JavaScript. In the onClick handler of the buttons, we can change the src property of
the image to whatever we want. This will cause the browser to fetch the new image image and
display it in place of the old one.

Image Rollovers

You might have seen a number of web pages where an image transforms when you move the mouse
over it. This can also be done using the above technique. Try moving your mouse over the image below.
Clicking on it will take you to my index.htm page.
Now, take a look at the code required for creating a link like the above one.

<A HREF="index.htm" onMouseOver="imgfan.src='fan.gif'"


onMouseOut="imgfan.src='fanoff.gif'">
<IMG NAME="imgfan" SRC="fanoff.gif"
WIDTH=61 HEIGHT=72 BORDER=0>
</A>

I will be putting up some advanced stuff for manipulating images as soon as I learn them myself.
Until then, try experimenting on your own.

You have created your first website but your page counter is not counting as fast as you thought
it would. The only people who visit seem to be your mom and your best friend. Mothers
understand but how do you explain this phenomena to your friend. It's simple really. Just
password protect your site. Although this won't increase the number of visitors, you can use it
explain why the numbers are not in the millions.

My first attempt at password protecting went something like this: Replace the page you want to
protect with another page that would ask the visitor for a username and password. When the
visitor clicks submit, the Javascript code on the page checks whether the username and password
match and redirect the visitor to the original page.The code is given below.

<FORM NAME="login">
Username: <INPUT NAME="username"><BR>
Password: <INPUT NAME="password" TYPE=PASSWORD><BR>
<INPUT TYPE=BUTTON VALUE="Login" onClick="verifyLogin()">
<INPUT TYPE=RESET>
</FORM>

<SCRIPT LANGUAGE="Javascript">
<!--
function verifyLogin()
{
var myForm = document.login;

if (myForm.username.value == "elvis" &&


myForm.password.value == "presley")
window.location.href = "secretpage.html";
else
alert("Unknown username or wrong password");
}
// -->
</SCRIPT>
Here is the actual form
Username:
Password:

It's pretty stright forward and it works. The only problem is that anyone can do a View|Source
and find out your username and password and also the address of the password protected page,
and that obviously is not good.

What we need is a method in which looking at the HTML source will reveal nothing about the
username, password or the target page. One such method that is commonly used is to generate
the target page name from what the user enters in the username and password fields and redirect
the browser to that page. Take a look at the modified verifyLogin() function.

<SCRIPT LANGUAGE="Javascript">
<!--
function verifyLogin()
{
var myForm = document.login;
window.location.href = myForm.username.value +
myForm.password.value +
".html";
}
// -->
</SCRIPT>

All that the function now does is to concatenate the username, the password and ".html" and
redirect the browser to that location. So if your visitor entered secret as the username and page as
the password, he/she would be taken to secretpage.html. If on the other hand, they don't know
the correct username and password and entered say foo as the username and bar as the password,
they would be redirected to the non-existant foobar.html and get an error saying that the page
was not found.

There is another reason for wanting to password protect your pages other than the one mentiond
at the beginning of this page, and that is you actually have something that you don't want to make
public. My advice to you is do not use Javascript based password protection schemes.

You might also like