Você está na página 1de 104

Unit-I

1.1 Introduction to HTML:


Many times you used the internet may be for the purpose of E-mail or for
searching the contents on web. But how a web page is created? The answer is by using
HTML, or Hyper Text Markup Language is the basis for creating any webpage. HTML is
neither a procedure language like C, FORTRON or Pascal; nor object-oriented language like
C++ or java.

HTML is a scripting language for WebPages and the output of programs can be
seen after using browser. These HTML documents are plain text files which the user can
create using a text editor like Notepad or Edit.

One of the mechanisms for controlling the layout of a structurally marked-up


document is SGML, Standard Generalized Markup Language. It is not a Markup Language,
but a Markup Meta Language, which means it, is a language for defining markup
languages; it allows you to define your own tags, each of which is used to mark a
particular sort of document element, such as a paragraph, section headings, or list. Unlike
SGML, HTML is only a markup language: it provides a set of tags suitable for marking up
web pages, but does not provide any way of defining new tags.

1. 2. World Wide Web (WWW):

A multimedia internet service which allows users to move from one document to
another through links that connects them together. World Wide Web is a repository of
information that was started by Berners Lee. When first time it was introduced only for
group of friends later it became the backbone of Internet. World Wide Web nowadays
changed as alternative term internet. But, an internet is collection of networks and totally
differs from World Wide Web. WWW is collection of web pages together where internet is
collection of networks. There is another term intranet which means that a private internet
service that is used for private use.

1. 3. HTML: (Hyper Text Markup Language)

Def: HTML is simply a collection of codes, called elements that are used to indicate the
structure and format of a document.

Hyper Text:

HTML is a Hyper text language because it supports font styled text, pictures,
graphics and animations and also it provides hyper links that used to browse the Internet
easily. Text becomes hypertext with addition of links that connects other hypertext
documents.

Markup Language:
HTML is markup Language because any text simply placed in the file is the data
content, and the text is shown as it is on browser.

HTML is markup language, which used to format text end information. Three
factors were essential for the formulation, they are

• Platform Independence

• Hyper Text and

• Semantic Structure

HTML Terms:

Tags: HTML is tag-based system. Tags are lexically distinguished from the text proper, by
enclosed in angle brackets or beginning with a backslash character. HTML provides a set of
tags suitable for marking up web pages. A tag is a special instruction for the browser,
which indicates that the given information after tag should be rendered according to the
given instruction.

A tag is made up of a left operator (<), a right operator (>) and a tag name
between these two operators (eg: <html>).

Syntax:

<tag name [parameter(s) [=value]]>

Optionally tag name contains one or more parameters, they may have values.

Elements: Elements in HTML consists of alphanumeric tokens with in angle brackets, such
as <B>,<HTML> ext. Most of the elements consist of paired tags: a start tag and end tag.

Ex: <B>content</B>

Some elements don’t require an end tag that elements are called empty elements.

Ex: <BR>, <p> (end is optional)

The HTML specification defines the type of content that an element encloses. This is known
as element’s content model.

Ex: <HEAD> content model contains only a small number of related elements,
such as <TITLE> and <META>

Attributes:

Tags can have attributes. Attributes can provide additional information about the
HTML elements on your page.

This tag defines the body element of your HTML page: <body>. With an added bgcolor
attribute, you can tell the browser that the background color of your page should be red,
like this:

<body bgcolor="red">.
This tag defines an HTML table: <table>. With an added border attribute, you can tell the
browser that the table should have no borders: <table border="0">

Attributes always come in name/value pairs like this: name="value".

Attributes are always added to the start tag of an HTML element.

1.3.1 HTML Rules and Guidelines:

1. HTML documents are structured documents.

HTML documents have a well- defined structure. The idea of a content


model

says that certain HTYML elements should occur only with in order. Ex <LI>

The structure of an HTML document is specifies by a document type


definition (DTD). A DTD defines what elements a document can contain,
their possible relationships to one another inside a document, and their
possible attributes and values. If the elements in a particular HTML
document agree with this formal definition, the document is said to be
valid.

2. Element names are not case-sensitive.

An element such as <html> is equivalent to <Html> or <HTML>

3. Attribute names are not case-sensitive.

<hr> is equivalent to <HR>, <HR NOSHADE> is equivalent to <HR


noshade>.

4. Attribute values may be case-sensitive.

The value of an attribute may be case-sensitive, especially of it refers to a file.

Ex: the filename in <img src=”filename.gif”> is not equal to <img

src=”FILENAME.gif”>

5. Attribute values should be quoted.

The actual attribute values may contain spaces or other special characters
if it

is enclosed by quotes.

Ex: <img src=”path” ALT=” the value”>

6. Element names can not contain spaces.

Browsers treat the first space encountered inside an element as the end of
an

element’s name and the beginning of it’s attributes.

Ex: <I M G >is wrong <IMG> is correct


7. Browsers collapse and ignore space characters in HTML content.

Browsers collapse any sequence of spaces, tabs and returns in an HTML

document in to a single space character.

8. HTML documents may contain comments.

HTML supports comments that are not displayed with in a browser widow.

<!—open tag for HTML comments and  closing tag.

9. Elements should nest.

Elements often contain other elements inside the document section that
they

enclose.

Ex: <B><I> correct </T></B>

10. Browsers ignore unknown elements.

Browsers ignore elements they don’t understand.

11. Browsers ignore unknown attributes.

As with elements, browsers ignore any attributes that they don’t


understand.

1.3.2 The structure of HTML Document:

<!DOCTYPE HTML PUBLIC “html version”>


<HTML>
<HEAD>
<TITLE>Document name </TITLE>
</HEAD>
<BODY>
markup text goes here
</BODY>
</HTML>
Explanation:

<!DOCTYPE>: an HTML document begins with a <!DOCTYPE> declaration,


indicating the version of HTML used by the document.

<HTML>: It encloses the actual document. It contains two primary sections, the
head and body, encloses by the <HEAD> and <BODY> elements.

<HEAD>: It encloses a document section that contains identification and


supplementary information about a document. But browsers generally don’t display this
information. Inside elements of this element model are

• <BASE>
• <ISINDEX>

• <LINK>

• <META>

• <OBJECT>

• <SCRIPT>

• <STYLE>

• <TITLE>

<BASE>: Specifies an absolute URL address that is used to provide server and directory

information for partially specified URL address called relative URLs, used with in

the document.

<ISINDEX>: Indicates that the document contains a searchable index.

<LINK>: specifies a special relationship between the current document and another
document.

<META>: uses names/ value pairs to provide Meta information about a document.

<OBJECT>: It allows programs and other binary objects to be directly embedded in a


webpage.

Ex: JavaApplets, Plug-ins, Active-X controls

<SCRIPT>: It allows programs written in a scripting language to be directly embedded in


a webpage.

<STYLE>: Encloses style specifications covering fonts, colors, positioning and other
aspects of contents presentations.

<TITLE>: It must be used in every HTML document. It gives an HTML document a title by
which it is known to browsers.

<BODY>: This is the area where you want to specify all common tags for creating desired
webpage. The body of a document is delimited by <BODY> and </BODY>. This is optional,
but should always be included common attributes for the <BODY> element affects the
colors for a document text, background and links.

HTM or HTML Extension?

When you save an HTML file, you can use either the .htm or the .html extension.
We have used .htm in our examples. It might be a bad habit inherited from the past when
some of the commonly used software only allowed three letter extensions. With newer
software we think it will be perfectly safe to use .html.

1.3.3 Basic HTML Tags:


The most important tags in HTML are tags that define headings, paragraphs and line
breaks.

Headings:

Headings are defined with the <h1> to <h6> tags. <h1> defines the largest
heading. <h6> defines the smallest heading.

<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>

HTML automatically adds an extra blank line before and after a heading.

Paragraphs:

One of the most important structuring elements is the paragraph element.


Surrounding text with the <p> and </P> tags indicates hat the text is a lexical paragraph
unit.

Paragraphs are defined with the <p> tag.

<p>This is a paragraph</p>
<p align=”center”>This is another paragraph</p>

HTML automatically adds an extra blank line before and after a paragraph.

The align attribute makes it possible to specify a left, right, or center alignment,
and also it has a justify value to justify all text in the paragraph.

Line Breaks

The <br> tag is used when you want to end a line, but don't want to start a new
paragraph. The <br> tag forces a line break wherever you place it.

<p>This <br> is a para<br>graph with line breaks</p>

The <br> tag is an empty tag. It has no closing tag.

Pre Formatted Text

It can be used to surround text that should be formatted by the browser. The text
enclosed with in the <PRE> tags retains all spacing and returns, and doesn’t reflow when
the browser is resized.

<pre> This is P R E F O R M E D
T
E
X
T </pre>

Basic HTML Tags

Tag Description

<html> Defines an HTML document

<body> Defines the document's body

<h1> to <h6> Defines header 1 to header 6

<p> Defines a paragraph

<br> Inserts a single line break

<hr> Defines a horizontal rule

<!--> Defines a comment

Text Formatting:

HTML defines a lot of elements for formatting output, like bold or italic text.

Text Formatting Tags

Tag Description

<b> Defines bold text

<big> Defines big text

<em> Defines emphasized text

<i> Defines italic text

<small> Defines small text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<ins> Defines inserted text

<del> Defines deleted text

"Computer Output" Tags


Tag Description

<code> Defines computer code text

<kbd> Defines keyboard text

<samp> Defines sample computer code

<tt> Defines teletype text

<var> Defines a variable

<pre> Defines preformatted text

Citations, Quotations, and Definition Tags

Tag Description

<abbr> Defines an abbreviation

<acronym> Defines an acronym

<address> Defines an address element

<bdo> Defines the text direction

<blockquote> Defines a long quotation

<q> Defines a short quotation

<cite> Defines a citation

<dfn> Defines a definition term

Text Formatting with FONT:

This tag is used for formatting text.

<font color=”red” size=”+1” face=”arial”>This is a text with font changes</font>

Color: it indicates the color of a formatted text. If you want to set font color for the
whole document you can use text attribute in a body tag with desired color value.

Size: it is used to change the size of the text being formatted.

Large size=”+x”, small size=”-x” x: the number of font size by which you want to
enlarge or diminish the text. The actual size lice between 1 to 7

Face: change the font of the text you want to formatted.

Character Entities:
Some characters have a special meaning in HTML, like the less than sign (<) that
defines the start of an HTML tag. If we want the browser to actually display these
characters we must insert character entities in the HTML source.

A character entity has three parts: an ampersand (&), an entity name or a # and an entity
number, and finally a semicolon (;).

To display a less than sign in an HTML document we must write: &lt; or &#60;

The advantage of using a name instead of a number is that a name is easier to remember.
The disadvantage is that not all browsers support the newest entity names, while the
support for entity numbers is very good in almost all browsers.

Note that the entities are case sensitive.

Non-breaking Space

The most common character entity in HTML is the non-breaking space.Normally


HTML will truncate spaces in your text. If you write 10 spaces in your text HTML will
remove 9 of them. To add spaces to your text, use the &nbsp; character entity.

The Most Common Character Entities:

Result Description Entity Name Entity Number

non-breaking space &nbsp; &#160;

< less than &lt; &#60;

> greater than &gt; &#62;

& ampersand &amp; &#38;

" quotation mark &quot; &#34;

' apostrophe &apos; (does not work in IE) &#39;

Some Other Commonly Used Character Entities:

Result Description Entity Name Entity Number

¢ cent &cent; &#162;

£ pound &pound; &#163;

¥ yen &yen; &#165;

§ section &sect; &#167;

© copyright &copy; &#169;

® registered trademark &reg; &#174;


× multiplication &times; &#215;

÷ division &divide; &#247;

1.3.4 Lists:

Lists are block formatting elements that defines a block structure.

HTML supports three basic types of lists.

1. Ordered lists (<ol>)

2. unordered lists (<ul>)

3. Definition lists (<dl>)

Ordered lists:

An ordered list is a list of items. The list items are marked with numbers.

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>

Here is how it looks in a browser:

1. Coffee

2. Milk

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

<ol> element has three basic attributes.

1. Compact 2. Start 3. Type.

Compact: this attribute requires no value. It simply suggests that the browser attempt to
compact the list, to use less space on screen.

Type: this attribute of <ol> can be set to ‘a’ for lower case letters, ‘A’ for uppercase
letters, ‘i’ for lower case Roman letters, ‘I’ for upper case letters, ‘1’ is default value.

Start: this attribute takes a numeric value to begin the list numbering. Whether the type
attribute is a letter or numeral, the start must be number.

Unordered lists:

An unordered list is also a list of items. The list items are marked with bullets
(typically small black circles).

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>

Here is how it looks in a browser:

• Coffee

• Milk

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

Types of unordered list are disc, circle, square.

Definition lists:

A definition list is not a list of items. This is a list of terms and explanation of the
terms.A definition list starts with the <dl> tag. Each definition-list term starts with the
<dt> tag. Each definition-list definition starts with the <dd> tag.

<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>

Here is how it looks in a browser:

Coffee

Black hot drink

Milk

White cold drink

Inside a definition-list definition (the <dd> tag) you can put paragraphs, line breaks,
images, links, other lists, etc.

1.3.5 Links:

The most important capability of HTML is it’s ability to create hyperlinks to


documents else where on the server and on different servers and thereby make possible a
world-wide network of linked documents and information.

In HTML both text and images can act as anchors to link to other pages on the
web.

The Anchor Tag and the Href Attribute


HTML uses the <a> (anchor) tag to create a link to another document.

An anchor can point to any resource on the Web: an HTML page, an image, a
sound file, a movie, etc.

The syntax of creating an anchor:

<a href="url">Text to be displayed</a>

The <a> tag is used to create an anchor to link from, the href attribute is used to address
the document to link to, and the words between the open and close of the anchor tag will
be displayed as a hyperlink.

This anchor defines a link to W3Schools:

<a href="http://www.w3schools.com/">Visit W3Schools!</a>

The line above will look like this in a browser:

Visit W3Schools!

The Target Attribute

With the target attribute, you can define where the linked document will be
opened.

The line below will open the document in a new browser window:

<a href="http://www.w3schools.com/"
target="_blank">Visit W3Schools!</a>

Internal Linking:

The Anchor Tag and the Name Attribute

The name attribute is used to create a named anchor. When using named anchors we can
create links that can jump directly into a specific section on a page, instead of letting the
user scroll around to find what he/she is looking for.

Below is the syntax of a named anchor:

<a name="label">Text to be displayed</a>

The name attribute is used to create a named anchor. The name of the anchor can be any
text you care to use.

The line below defines a named anchor:

<a name="tips">Useful Tips Section</a>

You should notice that a named anchor is not displayed in a special way.
To link directly to the "tips" section, add a # sign and the name of the anchor to the end of
a URL, like this:

<a href="http://www.w3schools.com/html_links.asp#tips">
Jump to the Useful Tips Section</a>

A hyperlink to the Useful Tips Section from WITHIN the file "html_links.asp" will look like
this:

<a href="#tips">Jump to the Useful Tips Section</a>

1.3.6 Images:

An image plays an important role in web pages. The total look of a web page is
improved by using images. Another advantage of using images is these can be as
hyperlinks. The effect of web page is increased when it includes clickable images that
server as the source of a link. A common use of this facility is to create clickable icons or
buttons; another is to produce image catalogues consisting of small ‘thumbnail’ pictures;
clickable on a thumbnail causes a full-sized version of the picture to be displayed.

Images can be embedded inside documents using the <IMG> tag. Also we can
specify Align parameter for it. Default alignment is center. All browsers support GIF and
JPEG file fotmates for images and either of them can be used. As specified earlier, Images
can also be used as links where you click an image to follow a link. Images can include as
background for the entire web page by using BACKGROUND parameter of BODY tag.

<BODY BACKGROUND=”file name/address”>

If an image included in the current directory directly the filename can be used, other wise
specify the complete path of the image file.

<IMG> tag:

By using <IMG> tag we can include images on the web page. It has several
attributes like align, src, width, and height etc. The important parameter among them is
SRC because it specifies the location of the file. All these tags are described as follows:

SRC: specifies source file name that is image file name.

BORDER: specifies border width around the displayed image.

WIDTH and HEIGHT: These parameters specifies the image width and height
respectively. These can be given as pixel values or percentages.

ALT: specifies alternative information if image is not displayed because of browser


(text-based browser) or any other case like image not found

Common syntax:
<IMG SRC=”file name/address” [BORDER=n] [ALT=”textual message” [HEIGHT=n]
[WIDTH=n]>

Images as hyperlinks:

Before <IMG> tag if you specify anchor tag (<a>) then image converted as
hyperlink.

Ex: <a> <img src=”path” height=”200” width=”200”></a>

1.3.7 Tables:

Tables are one of the important concepts while displaying information on web
page. This is another way of formatting text. There are several types of tables come across
out day-to-day life like railway time tables, calendar, shopping list etc.

A large data stored in a table can be easily referred because it provides an


organized and systematic display of data. Table tags are very simple, but with variety of
attributes available to you, the application is somewhat complicated.

Simple table:

Tables are defined with the <table> tag. A table is divided into rows (with the
<tr> tag), and each row is divided into data cells (with the <td> tag). The letters td
stands for "table data," which is the content of a data cell. A data cell can contain text,
images, lists, paragraphs, forms, horizontal rules, tables, etc.

Ex:

<table border="1">
<caption> a simple table </caption>
<thead>
<tr>
<th>Heading</th>
<th>Another Heading</th>
</tr>
</thead>
<tbody>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</tbody>
</table>

To display a table with borders, you will have to use the border attribute. If you do
not specify a border attribute the table will be displayed without any borders. Sometimes
this can be useful, but most of the time, you want the borders to show.

The caption element assigns a text directly above the table in the browsers
window.

To display a table with header information, you will have to use thead element.
Headings in a table are defined with the <th> tag.

To display a table with body information, you will have to use tbody element. data
in a table are defined with the <td> tag.

Complex tables:

HTML provides many additional features for tables. The <COLGROUP> element is
used to group and format columns. Each COL element in the
<COLGROUP>..</COLGROUP> tags can format any number of columns, which specified
with SPAN attribute.

Ex:

<COLGROUP>
<COL ALIGN=”CENTER”>
<COL SPAN=”2” ALIGN=”LEFT”>
</COLGROUP>

You can add background color and background images by using BGCOLOR and
BACKGROUND attributes respectively. Spanning of cells is possible that is you can merge
some sequence of rows or columns with the help of ROWSPAN or COLSPAN attributes
respectively.

Ex:

<table border="1">
<caption> a simple rowspan </caption>
<tr> <td rowspan=”2”>element</td>
<td>element 1</td>
<tr><td colspan=”2”>element2</td>
</tr>
<tr><td>element4</td><td>element5</td></tr>
</table>

1.3.8 Forms:
In order to receive information from people, the language should provide some
interactive features in to it. For example scanf (--) in C, Text field class in Java.
Comparatively a graphical user interface screen is more attract then simple unformatted
text. HTML provides several user interface elements to accept data; the important among
them is Form. HTML form is used to create user interface screens.

Common user interface elements are label, text fields, buttons, radio buttons,
check boxes, text areas, password fields, combo boxes, list fields.

Creation of HTML forms:

The <FORM> tag is used to create HTML forms; it is the first elements for
specifying the form. End of the form is indicated by </FORM> tag. <FORM> tag has
several attributes and important among them is METHOD and ACTION. ACTION parameter
indicates path to this script. When the user submits the form where it should go is given in
ACTION parameter.

METHOD parameter specifies how the data entered in form is sent to the
destination, which may be web server. There area two methods of sending of information;
one is POST, which send the information along with the body of the HTML page, other one
GET, sends the data along with web page address that is appended to the URL. There are
several differences between posts and get method.

A form is defined with the <form> tag.

<form>
<input>
<input>
</form>

Input

The most used form tag is the <input> tag. The type of input is specified with the type
attribute. The most commonly used input types are explained below.

Text Fields

Text fields are used when you want the user to type letters, numbers, etc. in a form.

<form>
First name:
<input type="text" name="firstname">
<br>
Last name:
<input type="text" name="lastname">
</form>

How it looks in a browser:


First name:

Last name:

Note that the form itself is not visible. Also note that in most browsers, the width of the
text field is 20 characters by default.

Text Area:

Text areas are used when you want the user to type letters, numbers, etc. in a form. This
type of form component has its own element. The TEXTAREA element inserts a box into
the form. You specify the size of the box inside the opening <TEXTAREA> tag with the
ROWS attribute, which sets the number of rows appearing in the TEXTAREA. With the
COLS attribute, you specify how wide the text area should be.

<form>
comments:
<textarea name=”comments” rows=”4” cols=”36”>
</textarea>
</form>

Radio Buttons

Radio Buttons are used when you want the user to select one of a limited number of
choices.

<form>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
</form>

How it looks in a browser:

Male

Female

Note that only one option can be chosen.

Checkboxes

Checkboxes are used when you want the user to select one or more options of a limited
number of choices.

<form>
<input type="checkbox" name="bike">
I have a bike
<br>
<input type="checkbox" name="car">
I have a car
</form>

How it looks in a browser:

I have a bike

I have a car

The Form's Action Attribute and the Submit Button

When the user clicks on the "Submit" button, the content of the form is sent to another
file. The form's action attribute defines the name of the file to send the content to. The file
defined in the action attribute usually does something with the received input.

<form name="input" action="html_form_action.asp"


method="get">
Username:
<input type="text" name="user">
<input type="submit" value="Submit">
</form>

How it looks in a browser:

Submit
Username:

If you type some characters in the text field above, and click the "Submit" button, you will
send your input to a page called "html_form_action.asp". That page will show you the
received input.

Combo boxes:

<form>
options:
<select name=”rate”>
<option select>10
<option>9
<option>8
</form>

1.3.9 Creating and Using Image Maps

Image map is the process of creating an image in to individual clickable elements so that
user can click at any where of the image, and the respective portions html is going
to open. The image should be divided into logical sections, each individual section
act as separate hyperlink and respective state information can be displayed. The
concept of logical section is called image maps and the area that is used as
anchors for linking is called hotspots.

The required tag for creating an image map is <MAP> tag. All elements of an image map
are contained inside the <MAP> .. </MAP> tags. Using area tag identifies
individual logical sections. It contains SHAPE attribute that specifies shape of the
logical section. Another important attribute is COORDS that specifies coordinates
for the given shape. It also contains a ALT property, which specifies alternative
message for the logical sectioned map.

The procedure for creation of image map involves two steps. First step is defined all the
required logical section elements through MAP and AREA tags and give an ID or
name for the map. Second step is identify which image to be divided into logical
section and give the same ID or name that specified in MAP element in USEMAP
property of image. The name of map should be preceded by # symbol which
indicates the specified name include in the current document.

For example consider an image contains 400*400 size then you want to divide into two
sections. First section having rectangle coordinates as 0, 0,200,200 and second
logical section rectangle coordinates as 201,201,400,400. Now the map tag is as
follows

<map name=”pict”>
<area href=”first.html” shape=”rect” cords=”0,0,200,200” alt=”image1”>
<area href=”second.html” shape=”rect” cords=”201,201,400,400” alt=”image2”>
</map>
<img src=”req.gif” width=400 height=400 border=2 alt=”pic” usemap=”#pict”>

1.3.10 Frames:

With frames, you can display more than one HTML document in the same browser window.
Each HTML document is called a frame, and each frame is independent of the others.

The disadvantages of using frames are:

• The web developer must keep track of more HTML documents

• It is difficult to print the entire page

The Frameset Tag

• The <frameset> tag defines how to divide the window into frames

• Each frameset defines a set of rows or columns

• The values of the rows/columns indicate the amount of screen area each row/column
will occupy

The Frame Tag


• The <frame> tag defines what HTML document to put into each frame

In the example below we have a frameset with two columns. The first column is set to
25% of the width of the browser window. The second column is set to 75% of the width of
the browser window. The HTML document "frame_a.htm" is put into the first column, and
the HTML document "frame_b.htm" is put into the second column:

<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

2.3 Cascading Style Sheets:

 Style Sheets provide presentation information, redefining html tag effects


and adding new formatting information.

 They ‘cascade’ because, if there is more than one rule operating to format
some content, there is a hierarchy of rules taking precedent (the closest to
the content wins).

 There are 2 standards. CSS1 is level 1, which version 6 browsers. CSS2


includes positioning and printing information that they mostly support.

Style shee
selector property
body {background:
declar

h1 {font -weight:
Style sheets are three types:

1. inline Style sheets

2. Internal Style sheets

3. External Style sheets

2.3.1 Inline Style sheets:

– Inline styles are individual element’s style declared using the


STYLE attribute. Each CSS property followed by a colon and the
value of that attribute. Multiple properties separated by semicolons.
Inline styles override any other styles

<P STYLE = “font-size: 20 pt; color: #0000FF”>

Ex:

1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

2 <HTML>

4 <!-- Fig. 14.1: inline.html -->

5 <!-- Using inline styles -->

7 <HEAD><TITLE>Inline Styles</TITLE></HEAD>

9 <BODY>

10

11 <P>Here is some text</P>

12

13 <!-- The STYLE attribute allows you to declare inline -->

14 <!-- styles. Separate multiple styles with a semicolon. -->

15 <P STYLE = "font-size: 20pt">Here is some more text</P>

16 <P STYLE = "font-size: 20pt; color: #0000FF">Even more text</P>

17

18 </BODY>

19 </HTML>

Output:
2.3.2 Internal Style Sheet:

In internal style sheet the style sheet Begins with <STYLE TYPE = “text/css”> in
header section. Styles placed here apply to the whole document. TYPE attribute specifies
the MIME type. MIME is a standard for specifying the format of content. Other MIME types
include text/html, image/gif and text/javascript

• Declare CSS rules within STYLE element

– Each rule body begins and ends with a curly brace ({ and })

– Class declarations are preceded with a period and applied to elements only
of that specific class

– Each property is followed by a colon and the value of the property

– Multiple properties are separated by semicolons

• Generic font families

– Allow you to specify a type of font instead of a specific font

• Font-size property

– Relative sizes: xx-small, x-small, small, smaller, medium, large,


larger, x-large and xx-large

• Styles applied to an element (the parent element)

– Also apply to the elements inside that element (child elements)

This is also called embedded style sheets.


Ex:
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<HTML>
3
4<!-- Fig. 14.2: declared.html -->
5<!-- Declaring a style sheet in the header section. -->
6
7<HEAD>
8<TITLE>Style Sheets</TITLE>
9
10<!-- This begins the style sheet section. -->
11<STYLE TYPE = "text/css">
12
13 EM { background-color: #8000FF;
14 color: white }
15
16 H1 { font-family: Arial, sans-serif }
17
18 P { font-size: 18pt }
19
20 .blue { color: blue }
21
22</STYLE>
23</HEAD>
24
25<BODY>
26
27<!-- This CLASS attribute applies the .blue style -->
28<H1 CLASS = "blue">A Heading</H1>
29<P>Here is some text. Here is some text. Here is some text.
30Here is some text. Here is some text.</P>
31
33<P CLASS = "blue">Here is some more text. Here is some more text.
32<H1>Another Heading</H1>
4
34 Here is some <EM>more</EM> text. Here is some more
text.</P>
35

36 </BODY>

37 </HTML>

Output:

2.3.3 External Style Sheets:

• External linking

– Separate pages can all use same style sheet

– Only modify a single file to change styles across your site

• LINK element

– Specifies a relationship (REL attribute) between current document and


another document

<LINK REL = “stylesheet” TYPE = “text/css”

HREF = “styles.css”>

– LINK element can only be placed in header

– Other REL values

• next, previous allow you to link a series of documents

– Print all linked documents option

• Style sheets are reusable

Ex:
1A { text-decoration: none }

3A:hover { text-decoration: underline;

4 color: red;

5 background-color: #CCFFCC }

7LI EM { color: red;

8 font-weight: bold}

10UL { margin-left: 2cm }

11

12UL UL { text-decoration: underline;

13 margin-left: .5cm }
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<HTML>
3
4<!-- Fig. 14.5: imported.html -->
5<!-- Linking external style sheets -->
6
7<HEAD>
8<TITLE>Importing style sheets</TITLE>

9<LINK REL = "stylesheet" TYPE = "text/css" HREF = "styles.css">


10</HEAD>
11
12<BODY>
13
14<H1>Shopping list for <EM>Monday</EM>:</H1>
15<UL>
16<LI>Milk</LI>
17<LI>Bread
18 <UL>
19 <LI>White bread</LI>
20 <LI>Rye bread</LI>
21 <LI>Whole wheat bread</LI>
22 </UL></LI>
23<LI>Rice</LI>
24<LI>Potatoes</LI>
25<LI>Pizza <EM>with mushrooms</EM></LI>
26</UL>
27
28<A HREF = "http://food.com">Go to the Grocery store</A>
29
30</BODY>
31</HTML>

Output:
UNIT - 2

JavaScript:
JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, create cookies, and much more.

JavaScript is the most popular scripting language on the internet, and works in all major
browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera.

What is JavaScript?

• JavaScript was designed to add interactivity to HTML pages

• JavaScript is a scripting language (a scripting language is a lightweight programming


language)

• A JavaScript consists of lines of executable computer code

• A JavaScript is usually embedded directly into HTML pages

• JavaScript is an interpreted language (means that scripts execute without preliminary


compilation)

• Everyone can use JavaScript without purchasing a license

What can a JavaScript 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 will save 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
JavaScript How To...

The HTML <script> tag is used to insert a JavaScript into an HTML page.

How to Put a JavaScript into an HTML Page

<!DOCTYPE html PUBLIC “--//W3C//DTD HTML 4.0 Transitional //EN”>


<!—Fig 1. hello.html -->
<html>
<head>
<title>introduction</title>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>")
</script>
</head>
<body>
</body>
</html>

The code above will produce this output on an HTML page:

Hello World!

Example Explained

The DOCTYPE element indicates that the document type is an HTML 4.0 document.

To insert a JavaScript into an HTML page, we use the <script> tag (also use the type
attribute to define the scripting language). So, the <script type="text/javascript"> and
</script> tells where the JavaScript starts and ends. Java Scripts in a page will be
executed immediately while the page loads into the browser. This is not always what we
want. Sometimes we want to execute a script when a page loads, other times when a user
triggers an event.

Scripts in the head section: Scripts to be executed when they are called, or when an
event is triggered, go in the head section. When you place a script in the head section, you
will ensure that the script is loaded before anyone uses it.

Scripts in the body section: Scripts to be executed when the page loads go in the body
section. When you place a script in the body section it generates the content of the page.

Scripts in both the body and the head section: You can place an unlimited number of
scripts in your document, so you can have scripts in both the body and the head section.

The word document.write is a standard JavaScript command for writing output to a


page. It instruct the browser’s JavaScript interpreter to perform an action, namely to
display in the web page the string of characters contained between the double quotation
(“) marks. The document object, which represents the html document currently being
displayed in the browser. The document object allows a script programmer to specify HTML
text to be displayed in the HTML document. The term object normally implies that
attributes (data) and behaviors (methods) are associated with the object. We call the
documents object’s writeln method to write a line of html text in the html document being
displayed. The parentheses following the method name writeln contain the arguments that
the method requires to perform its task. Method writeln instructs the browser to display
the argument string. If the string contains html elements, the browser interprets these
elements and renders them on the screen.

By entering the document.write command between the <script type="text/javascript">


and </script> tags, the browser will recognize it as a JavaScript command and execute the
code line. In this case the browser will write Hello World! to the page. With traditional
programming languages, like C++ and Java, each code statement has to end with a
semicolon.

Many programmers continue this habit when writing JavaScript, but in general, semicolons
are optional! However, semicolons are required if you want to put more than one
statement on a single line.

Note: If we had not entered the <script> tag, the browser would have treated the
document.write("Hello World!") command as pure text, and just write the entire line on
the page.

Using an External JavaScript

Sometimes you might want to run the same JavaScript on several pages, without having
to write the same script on every page.

To simplify this, you can write a JavaScript in an external file. Save the external JavaScript
file with a .js file extension.

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>

Note: Remember to place the script exactly where you normally would write the script!

JavaScript Popup Boxes

In JavaScript we can create three kinds of popup boxes: Alert box, Confirm box, and
Prompt box.
Alert Box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax:

alert("sometext")

Ex:

<html>
<head>
<script type="text/javascript">
function disp_alert()
{
alert("Hello again! This is how we" + '\n' + "add line breaks to an alert
box!")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="disp_alert()" value="Display alert box">
</form>
</body>
</html>

Explanation:

onclick is an event. It fires some action when the user can click that button. In this
example it executes disp_alert function when the user clicks that button.

Confirm Box

A confirm box is often used if you want the user to verify or accept something. When a
confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the
user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax:

confirm("sometext")

Ex:
<html>
<head>
<script type="text/javascript">
function disp_confirm()
{
var name=confirm("Press a button")
if (name==true)
{
document.write("You pressed the OK button!")
}
else
{
document.write("You pressed the Cancel button!")
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="disp_confirm()" value="Display a
confirm box">
</form>
</body>
</html>

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed
after entering an input value. If the user clicks "OK" the box returns the input value. If the
user clicks "Cancel" the box returns null.

Syntax:

prompt("sometext","defaultvalue")

Ex:

<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your name","")
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?")
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="disp_prompt()" value="Display a prompt
box">
</form>
</body>
</html>

Some common escape sequences:

Escape Sequences Description


\n New Line
\t Horizontal Tab
\r Carriage return
\\ Backslash
\” Double Quote
\’ Single Quote

JavaScript Variables

A variable is a "container" for information you want to store. A variable's value can change
during the script. You can refer to a variable by name to see its value or to change its
value.

Rules for variable names:

• Variable names are case sensitive

• They must begin with a letter or the underscore character

IMPORTANT! JavaScript is case-sensitive! A variable named strname is not the same as a


variable named STRNAME!

Declare a Variable

You can create a variable with the var statement:

var strname = some value

You can also create a variable without the var statement:


strname = some value

Assign a Value to a Variable

You can assign a value to a variable like this:

var strname = "Hege"

Or like this:

strname = "Hege"

The variable name is on the left side of the expression and the value you want to assign to
the variable is on the right. Now the variable "strname" has the value "Hege".

Lifetime of Variables

When you declare a variable within a function, the variable can only be accessed within
that function. When you exit the function, the variable is destroyed. These variables are
called local variables. You can have local variables with the same name in different
functions, because each is recognized only by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it.
The lifetime of these variables starts when they are declared, and ends when the page is
closed.

JavaScript Operators

Many scripts perform arithmetic calculations. So the operators are very useful. Bellow is
given the types of operators.

Arithmetic Operators

The arithmetic operators are summarized bellow.

Operator Description Example Result


+ Addition x=2 4
y=2
x+y

- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y

/ Division 15/5 3
5/2 2.5

% Modulus (division remainder) 5%2 1


10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--

Assignment Operators

Operator Example Is The Same As


= x=y x=y

+= x+=y x=x+y
-= x-=y x=x-y

*= x*=y x=x*y
/= x/=y x=x/y

%= x%=y x=x%y

Comparison Operators

Operator Description Example

== is equal to 5==8 returns false

=== is equal to (checks for both value and type) x=5


y="5"
x==y returns true
x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example


&& and x=6
y=3
(x < 10 && y > 1) returns true

|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true

String Operator

A string is most often text, for example "Hello World!” To stick two or more string
variables together, use the + operator.
txt1="What a very"
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!”

To add a space between two string variables, insert a space into the expression, OR in one
of the strings.

txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
or
txt1="What a very "
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!".

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable


based on some condition.

Syntax

variablename=(condition)?value1:value2

Javascript applies the operators in arithmetic expressions in a precise sequence


determined by the following rules of operator precedence.

Operators in expressions contained between a left parenthesis and its corresponding right
parenthesis are evaluated first. Thus, parenthesis may be used to force the order
of evaluation to occur in any sequence desired by the programmer. Parentheses
are said o be at the highest level of precedence. In case of nested or embedded
parentheses, the operators in the innermost pair of parentheses are applied first.

Multiplication, division and modulus operators are applied next. If an expression contains
several multiplications, division, modulus operations, operators are applied from
left to right.

Addition and subtraction operators reapplied last. If an expression contains several


addition and subtraction operations, operators are applied from left to right.

The rules of operator precedence enable JavaScript to apply operators in the correct order.
When we say that operators are applied from left to right, we are referring to the
associative of the operators- the order in which operators of equal priority are
evaluated.
Control Structures:

Algorithms:

Executing a series of actions in a specific order can solve any computing problem.
A procedure for solving a problem in terms of

The actions to be executed, and

The order in which these actions are to be executed.

Is called an algorithm.

Pseudocode

Pseudocode is an artificial and informal language that helps programerrs develop


algorithms. The pseudocode is useful for developing algorithms that will be
converted to structured portions of JavaScript programs. Pseudocode is similar to
everyday English; it is convenient and user friendly, although it is not an actual
programming language.

The style of pseudocode consisit purely of characters.

Control structures:

Normally, statements in a program are executed one after the other in the order in
which they are written. This is called sequential execution. The programmer may
specify the next statement to be executed may be one other than the next one in
sequence. This is called transfer of control.

The control structures are three types.

Sequential structure

Selection structure

Repetition structure.

Conditional Statements

Conditional statements in JavaScript are used to perform different actions based on


different conditions.

In JavaScript we have the following conditional statements:

• if statement - use this statement if you want to execute some code only if a specified
condition is true

• if...else statement - use this statement if you want to execute some code if the
condition is true and another code if the condition is false

• if...else if....else statement - use this statement if you want to select one of many
blocks of code to be executed
• switch statement - use this statement if you want to select one of many blocks of
code to be executed

If Statement

You should use the if statement if you want to execute some code only if a specified
condition is true.

Syntax

if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!

Example 1

<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date()
var time=d.getHours()

if (time<10)
{
document.write("<b>Good morning</b>")
}
</script>

Example 2

<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()

if (time==11)
{
document.write("<b>Lunch-time!</b>")
}
</script>

Note: When comparing variables you must always use two equals signs next to each
other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code
only if the specified condition is true.

If...else Statement

If you want to execute some code if a condition is true and another code if the condition is
not true, use the if....else statement.

Syntax

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example

<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()

if (time < 10)


{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>

If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of
lines to execute.

Syntax

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>")
}
else
{
document.write("<b>Hello World!</b>")
}
</script>

JavaScript Switch Statement

Conditional statements in JavaScript are used to perform different actions based on


different conditions.
The JavaScript Switch Statement
You should use the switch statement if you want to select one of many blocks of code to
be executed.
Syntax

switch(n)
{
case 1:
execute code block 1
break
case 2:
execute code block 2
break
default:
code to be executed if n is
different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.

Example

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}
</script>

JavaScript Loops

Loops in JavaScript are used to execute the same block of code a specified number of
times or while a specified condition is true.

In JavaScript there is two different kinds of loops:

• for - loops through a block of code a specified number of times


• while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)

code to be executed

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue
to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any
comparing statement.

<html>

<body>

<script type="text/javascript">

var i=0

for (i=0;i<=10;i++)

document.write("The number is " + i)

document.write("<br />")

</script>

</body>

</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The while loop

The while loop is used when you want the loop to execute and continue executing while
the specified condition is true.

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue
to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

<html>
<body>
<script type="text/javascript">
var i=0
while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
</script>
</table>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop

The do...while loop is a variant of the while loop. This loop will always execute a block of
code ONCE, and then it will repeat the loop as long as the specified condition is true. This
loop will always be executed once, even if the condition is false, because the code is
executed before the condition is tested.

do
{
code to be executed
}
while (var<=endvalue)

Example

<html>
<body>
<script type="text/javascript">
var i=0
do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0)
</script>
</table>
</body>
</html>
Result

The number is 0

JavaScript For...In Statement

The for...in statement is used to loop (iterate) through the elements of an array or through
the properties of an object.

The code in the body of the for ... in loop is executed once for each element/property.

Syntax

for (variable in object)


{
code to be executed
}

The variable argument can be a named variable, an array element, or a property of an


object.

Example

Using for...in to loop through an array:

<html>
<body>
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
</body>
</html>

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows after
the loop (if any).

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break}
document.write("The number is " + i)
document.write("<br />")
}
</script>
</table>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2

Continue

The continue command will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue}
document.write("The number is " + i)
document.write("<br />")
}
</script>
</table>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript Functions

A function is a reusable code-block that will be executed by an event, or when the function
is called.

To keep the browser from executing a script as soon as the page is loaded, you can write
your script as a function.

A function contains some code that will be executed only by an event or by a call to that
function.

You may call a function from anywhere within the page (or even from other pages if the
function is embedded in an external .js file).

Functions are defined at the beginning of a page, in the <head> section.

Example

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

If the line: alert("Hello world!!"), in the example above had not been written within a
function, it would have been executed as soon as the line was loaded. Now, the script is
not executed before the user hits the button. We have added an onClick event to the
button that will execute the function displaymessage() when the button is clicked.

You will learn more about JavaScript events in the JS Events chapter.

How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}

var1, var2, etc are variables or values passed into the function. The { and the } defines
the start and end of the function.

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function
must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that
you must call a function with the exact same capitals as in the function name.

The return Statement

The return statement is used to specify the value that is returned from the function.

So, functions that are going to return a value must use the return statement.

Example

The function below should return the product of two numbers (a and b):

function total(a,b)
{
x=a*b
return x
}

When you call the function above, you must pass along two parameters:

product=total(2,3)

The returned value from the total() function is 6, and it will be stored in the variable called
product.

Arrays

Array: a composite data type that holds a collection of data elements than can be
referenced by their index number

An array is a group of consecutive memory location that all share a common name with
homogeneous data type. Depends on the size of the data types the next memory location
is allocated.

According to JavaScript it is not having any common data type, type less language, so
it depends on the type of data you are storing in it. Observe the following array of
numbers, which are having different values with consecutive memory locations.

Numbe 6 1
r[0] 34 260

Numbe 1 1
r[1] 24 262

Numbe - 1
r[2] 65 264

Numbe 1 1
r[3] 2 266

Numbe 1 1
r[4] 1 268

Numbe 1 1
r[5] 34 270

Array name index/ values memory

position
In the figure array elements are sharing a common name ‘numbers’. To refer any
element from the array of values, JavaScript provides square brackets along with index or
subscript. An index is a position number in an array. Array name along with index gives
you an element in that array. In general the first element in array started with index 0 that
is zeroth element is the first element.

JavaScript provides facilities to declare arrays by using new operator. This language
treats arrays as objects and has many methods to manipulate them.

Creating Arrays

There are a few different ways to create an array. The first three involve the Array( )
constructor, and the last is the array literal.

The Array Constructor

The arrays constructor is used on the right hand side of a combined variable declaration
and assignment statement. It takes the following form:

var aName = new Array( );

If you declare a variable to be an array and do not pass any arguments with the
Array( ) constructor, you create an empty array with no elements. Since JavaScript arrays
are dynamic, this is not a problem.

Dynamic just means you don't have to tell JavaScript in advance how large the array
will be.

// single argument method

var aName = new Array(6);

If you declare a variable to be an array and pass a single integer as an argument with
the Array( ) constructor, you create an array with the specified number of elements. None
of the elements have any value assigned to them. The code above creates an array with
six elements, all of which have a value of undefined. What this method does is set the
length of the array to the value specified. You can check the array length by testing the
value of arrayName.length, where arrayName is replaced by the name of the array to be
tested.

// multiple argument method

var aName = new Array(20, 1, 7, 'top', 'love');


If you declare a variable to be an array and pass more than one arguement with the
Array( ) constructor, you create an array with the number of elements being equal to the
number of data values specified.

Each element will have the value specified in the list for that position. The above array
will have five elements with the first element having a value of 20 and the fifth element
having a value of "love". This technique does not work in JavaScript 1.2.

What happens if you want to create an array that just has one integer element ? The
answer is that you can't, at least not with the Array( ) constructor.

Since you can have empty elements, so you can just use Array(7,''), or you can define
the array to have a length of one and then assign a value in the next step, or you can use
an array literal.

Array Literals

Instead of using the Array constructor, an array literal allows you to assign an array of
values directly to a variable. This is done by including those values in square brackets in

the declaration and assignment statement.

var aName = [20, 1, 7, 'top', 'love'];

Whenever you assign a list of values enclosed in square brackets to a variable in a


variable declaration statement, JavaScript assumes that you are declaring an array. This
allows various array tricks.

• You can pass it undefined values by passing nothing between the commas in a
comma separated list.

• You can create an array of length 1 with an integer value defined at the time of
declaration.

• You can assign an array of values to an existing variable. This will overwrite the
previous value.

// array with undefined values

var aName = [1,,3,,5];

// array with length of 1

var aName = ['bob'];

// array assigned to an existing variable

var aName = 752;

aName = [1,2,3,4,5];
You should try to use the Array constructor instead of array literals when possible. If
nothing else, it makes your code much easier to read. Easy to read code tends to hide
fewer mistakes.

Working with Arrays

You access elements of the array by using the array name followed by square brackets,
aName[iNum]. The square brackets contain the number of the array element to be
referenced.

In JavaScript, arrays start with position zero ( 0 ), so the array elements are numbered
zero through length minue one. In other words, element one is is position zero, and
element ten is in position nine, etc.

// assigning a value

aName[1] = 7;

// reading a value

b = aName[1];

If you have nested arrays, then you just refer to the position in the array by lining up
values in square brackets after the array name.

var aName = new Array();

aName[0] = [1,2,3];

aName[1] = ['a','b','c'];

// equates to

aName[0][0] == 1;

aName[0][1] == 2;

aName[0][2] == 3;

aName[1][0] == 'a';

aName[1][1] == 'b';

aName[1][2] == 'c';

If we use make pretend we can use parentheses to set to define groupings and set
order of precedence, we get something that looks like this:

( ( (arrayName[idx1]) [idx2]) [idx3]) etc.

The index operator [idx3] operates on the expression arrayName[idx1][idx2], the index
operator [idx2] operates on the expression arrayName[idx1], and the index operator
[idx1] operates on the expression arrayName, which is the name of the array.
As if we were using parentheses, first the element specified by [idx1] is found, which in
this case is an array, then within that array the sub-element specified by [idx2], etc.

Associative Arrays

Since JavaScript allows for associative arrays, you can also assign values associated
with string values that serve as the index for the element instead of a number. Assigning
an element value this way will place it in the next available open slot.

In the following code, the fourth element (aName[3]) will have the name of newEl and
a value of 4.

var aName = [20, 1, 7];

aName['newEl'] = 4

In order to work with array values you need to refer to the array elements and not the
array itself.

This code is wrong

var aName = Array(1, 'cat', 2, 'dog');

if (aName == 'dog')

[...]

This code is right

var aName = Array(1, 'cat', 2, 'dog');

if (aName[3] == 'dog')

[...]

Adding Elements to an Array

With JavaScript, the length of an array is just its current length. The following is a

perfectly valid set of statements.

var aName = new Array(10);

aName[20] = 'top';

After these two statements run, the array will contain twenty-one elements, all of them
undefined except for the twenty-first element (aName[20]). Don't forget we started with
zero. In other words, you can add elements to the end of the array with no problem.

JavaScript makes use of what are called sparse arrays, which means that no matter
how many elements there are in the array, it only makes space in memory for those that
have been specificially declared. The above array would only have stored information on
eleven elements, aName[0] through aName[9] and aName[20].

On the other hand, if you do a for... in statement, it will still walk through every
element that could potentially have a value. On other words, from zero to the highest
position declared, in sequence, without skipping any, even if they are empty. This is not a
problem for twenty-one elements, but potentially a big problem if the first value is in
position aName[1000000].

Accessing Arrays

You can refer to a particular element in an array by referring to the name of the array
and the index number. The index number starts at 0.

The following code line:

document.write(mycars[0])

will result in the following output:

Saab

Example:

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

2. <HTML>

3. <!-- Fig. 1: InitArray.html -->

4. <HEAD>

5. <TITLE>Initializing an Array</TITLE>

6.

7. <SCRIPT LANGUAGE = "JavaScript">

8. // this function is called when the <BODY> element's

9. // ONLOAD event occurs

10. function initializeArrays()

11. {

12. var n1 = new Array( 5 ); // allocate 5-element Array

13. var n2 = new Array(); // allocate empty Array

14. // assign values to each element of Array n1


15. for ( var i = 0; i < n1.length; ++i )

16. n1[ i ] = i;

17. // create and initialize five-elements in Array n2

18. for ( i = 0; i < 5; ++i )

n2[ i ] = i;

19. outputArray( "Array n1 contains", n1 );

20. outputArray( "Array n2 contains", n2 );

21. }

22. // output "header" followed by a two-column table

23. // containing subscripts and elements of "theArray"

24. function outputArray( header, theArray )

25. {

26. document.writeln( "<H2>" + header + "</H2>" );

27. document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>"

28. document.writeln( "<TR><TD WIDTH = +


"<TD><B>Value</B></TR>" );

29. for ( var i = 0; i < theArray.length; i++ )

30. document.writeln( "<TR><TD>" + i + "<TD>" +

31. theArray[ i ] + "</TR>" );

32. document.writeln( "</TABLE>" );

33. }

34. </SCRIPT>

35. </HEAD><BODY ONLOAD = "initializeArrays()"></BODY>

36. </HTML>

Script output:
Multi-Dimensional Arrays

JavaScript doesn't actually have support for multi-dimensional arrays, but you can nest
arrays. For most programming purposes, nested arrays are equivalent to multi-
dimensional arrays. Therefore we are not going to worry about the differences between
them here.

To create a nested array, you just define an array element as being an array.

var outerA = new Array();

outerA[0] = new Array();

outerA[1] = new Array();

outerA[2] = new Array();

When using array literals, the same effect can be achieved by nesting square brackets.

var aName = [[1,2,3],['a','b','c']];

// is the same as

var aName = new Array();

aName[0] = [1,2,3];

aName[1] = ['a','b','c'];

Pass by Value / Pass by Reference

When passing a single value as an argument to a function you must refer to the
element being passed, not the array itself. If you just use the array name, then what you
are passing is the array, not its values. It is also important to understand the difference
between pass by value and pass by reference with arrays.

Primitive data types are passed by value. This means that when you pass them to a
function or use them in an assignment statement, what gets passed is the value, not the
variable itself. A copy of the value is made to be passed to the function or variable.

Arrays and objects, on the other hand, are passed by reference. This means that when
you pass them to a function or use them in an assignment statement, the reference to the
variable is passed. No new copy is created. Instead, the function argument or variable is
pointed to, or set to reference, the same location in memory. Thus, any changes you make
affect the original.

Array elements are passed based on the value of its contents; it is the array itself that
is automatically passed by reference.

Pass by value:

// b will still equal two after this code has run

function a(b) {

return b+2;

var b = 2;

c = a(b);

// b[1] still equals 2 again

function a(b) {

return b+2;

var b = new Array [1,2,3];

c = a(b[1]);

Pass by reference:

// b[1] will equal four after this code has run

function a(b) {

return b[1]+2;

var b = new Array [1,2,3];

c = a(b[1]);
Also two different arrays are not equal unless they reference the same location in
memory.

// This if statement will equate to true

var a = new Array(1, 2, 3);

var b = a;

if (a == b) {

// This if statement will equate to false

var a = new Array(1, 2, 3);

var b = new Array(1, 2, 3);

if (a == b) {

If you want to compare the values of array elements, then you have to compare the
values of individual array elements.

Example:

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

2. <HTML>

3. <!-- Fig. 2: PassArray.html -->

4. <HEAD>

5. <TITLE> Passing Arrays and Individual Array Elements to Functions

6. </TITLE>

7. <SCRIPT LANGUAGE = "JavaScript">

8. function start()

9. {

10. var a = [ 1, 2, 3, 4, 5 ];

11. document.writeln( "<H2>Effects of passing entire " +

12. "array call-by-reference</H2>" );

13. outputArray("The values of the original array are: ", a );


14. modifyArray( a ); // array a passed call-by-reference

15. outputArray("The values of the modified array are: ", a );

16. document.writeln( "<H2>Effects of passing array " + "element

17. call-by-value</H2>" + "a[3] before modifyElement: " +


a[ 3 ] );

18. modifyElement( a[ 3 ] );

19. document.writeln("<BR>a[3] after modifyElement: " + a[ 3 ] );

20. }

21. // outputs "header" followed by the contents of "theArray"

22. function outputArray( header, theArray )

23. {

24. document.writeln(header + theArray.join( " " ) + "<BR>" );

25. }

26. // function that modifies the elements of an array

27. function modifyArray( theArray )

28. {

29. for ( var j in theArray )

30. theArray[ j ] *= 2;

31. }

32. // function that attempts to modify the value passed

33. function modifyElement( e )

34. {

35. e *= 2;

36. document.writeln( "<BR>value in modifyElement: " + e );

37. }

38. </SCRIPT>

39. </HEAD><BODY ONLOAD = "start()"></BODY>

40. </HTML>
Script output

Common Array Methods

Since arrays and object are in many ways interchangeable in JavaScript, it would
follows that arrays have methods, just as objects do. We discuss methods in detail when
we talk about objects, but for now let us look at the basics of array methods. Almost all of
the methods of arrays are non-static.

A static method is one that can be used like a function, independent of any specific
array or object. Conversely, non-static arrays must occur as properties of specific
instances of an array. For instance, assume for the following that arr01 and arr02 are both
arrays:

// This is not a valid command

vName = concat(arr01, arr02);

// This is a valid command and concatenates arr02 to arr01

arr01.concat(arr02);

Join and reverse

These methods convert the elements of an array to strings and then join the string
together into one long string. It returns this string for assignment. It does not change the
contents of the array. Join joins the elements in order, while reverse joins them in reverse
order.

Unless told otherwise, they will separate the elements in the string with commas.
You can override this by specifying a string as an argument for the method. This string is
used to separate the elements.
// this will leave s with the value of '1,2,3'

var aName = new Array [1, 2, 3];

s = aName.join();

// this will leave s with the value of '1 -- 2 -- 3'

s = aName.join(' -- ');

// this will leave s with the value of '3, 2' 1'

s - aName.reverse(', ');

Sort

This method sorts the array into alphabetical order, or, more specifically, ASCII
value order. In other words, the sort is case sensitive.

If you want to sort in a different order, you pass a function as an argument for the
method. The function should compare two values and return a value that determines the
order to sort them in. This value should be a negative number if the first item comes first,
a positive number if the second item should come first, and zero if the two items are equal
and can occur in either order. This method changes the contents of the array.

// to sort in ASCII order

aName.sort( );

// to sort by function

aName.sort(someFuncName(a, b));

Example:

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

2. <HTML>

3. <!-- Fig.3 sort.html -->

4. <HEAD>

5. <TITLE> sorting an array with array method sort

6. </TITLE>

7. <SCRIPT LANGUAGE = "JavaScript">

8. function start()

9. {
10. var a = [ 10,1, 8, 3,6, 5, 2, 7, 4];

11. document.writeln( "<H1>Sorting an Array</H1>" );

12. outputArray( "Data items in original order: ", a );

13. a.sort( compareIntegers ); // sort the array

14. outputArray( "Data items in ascending order: ", a );

15. }

16. // outputs "header" followed by the contents of "theArray"

17. function outputArray( header, theArray )

18. {

19. document.writeln( "<P>" + header + theArray.join( " " ) + "</P>" );

20. }

21. // comparison function for use with sort

22. function compareIntegers( value1, value2 )

23. {

24. return parseInt( value1 ) - parseInt( value2 );

25. }

26. </SCRIPT>

27. </HEAD><BODY ONLOAD = "start()"></BODY>

28. </HTML>

Output:
Concat

This function concatenates another array to the current array. The new array is
appended at the end.

Elements that are themselves arrays are linearized and included as a series of
elements. This linearizing only occurs to one level of nesting. If that doesn't make sense,
then just avoid concatenating nested arrays.

// this code will concatenate arr02 to arr01

// arr01 will then equal (1, 2, 3, 4, 5, 6)

var arr01 = new Array(1, 2, 3);

var arr02 = new Array(4, 5, 6);

arr01.concat(arr02);

// this code will concatenate arr02 to arr01

// arr01 will then equal (1, 2, 3, 4, 5, 6, 7)

// note that arr02[2] equals the array containing

// the values (6, 7)

var arr01 = new Array(1, 2, 3);

var arr02 = new Array(4, 5, [6, 7]);

arr01.concat(arr02);

Slice and splice

These methods work with sub-arrays. Slice slices out a section of the array. It
takes two arguments, the starting position and the position after the ending position. If
either number is negative it is counted from the end of the string. Slice does not change

the array. It returns a value that needs to be assigned to some variable.

var aName = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

a = aName.slice(0,4); // returns (1, 2, 3)

a = aName.slice(5); // returns (6, 7, 8, 9)

a = name.slice(2, -2); // returns (3, 4, 5, 6, 7)

Splice inserts one array in another in a specified location, as well as deleting elements
from an array. It can both add and delete.

It takes a number of arguments.


• The first is the location to start the splice.

• The second is the number of elements to cut out. If omitted, then everything after
the start point is cut out.

• All arguments after that are elements to be added in at the location.

This method changes the array. Anything cut out of the array is returned from the
method and can be passed to a variable.

// this would set a to (4, 5, 6)

// and aName to (1, 2, 3)

var aName = new Array(1, 2, 3, 4, 5, 6);

a = aName.splice(2);

// this would set aName to (1, 2, 5, 6)

// and a to (3, 4)

var aName = new Array(1, 2, 3, 4, 5, 6);

a = aName.splice(2, 2);

// this would set aName to (1, 2, 'c', 'd', 5, 6)

// and a (3, 4)

var aName = new Array(1, 2, 3, 4, 5, 6);

a = aName.splice(2, 2, 'c', 'd');

The splice method is new and is not as well supported as the slice method. Here is
the same process performed with slice and with splice. Full support of splice will make
code just a little easier to read.

// aName set to (1, 2, 'c', 'd', 5, 6) with slice

var aName = new Array(1, 2, 3, 4, 5, 6);

var newName = Array( );

b = aName.slice(4);

a = aName.slice(0, 2);

newName.concat(a, 'c', 'd', c);

// aName set to (1, 2, 'c', 'd', 5, 6) with splice

var aName = new Array(1, 2, 3, 4, 5, 6);

aName.splice(2, 2, 'c', 'd');

chop() - Used to truncate the last character of a all strings that are part of an array.

This method is not defined so it must be written and included in your code.
// causes the values of aName to become :

//look out duck

var aName = new Array(“look out!”,”duck”);

aName.chop();

grep(searchstring) - Takes an array and returns those array element strings that
contain matching strings. This method is not defined so it must be written and included in
your code.

var words = new Array(“limit”,”lines”,”finish”,”complete”,”in”,”out”);

inwords=words.grep(“in”)

//the array , inwords,will be:

//lines, finish

pop() - Pops the last string off the array and returns it. This method is not defined so it
must be written and included in your code.

var words = new Array(“limit”,”lines”,”finish”,”complete”,”in”,”out”);

var lastword=words.pop()

// the value of the string lastword is:

// out

push(strings) - Strings are placed at the end of the array. This method is not defined
so it must be written and included in your code.

var words = new Array(“limit”,”lines”,”finish”);

words.push(“complete”,”in”,”out”)

//the array , words, will be:

// limit, lines, finish, complete, in, out

shift() - Decreases array element size by one by shifting the first element off the array
and returning it. This method is not defined so it must be written and included in your
code.

var words = new Array(“limit”,”lines”,”finish”,”complete”,”in”,”out”);

var word=words.shift()

// the array words will be:

// in, complete, finish, lines, limit


// the string word will be: out

unshift() - Places elements at the start of an array

var words = new Array(”finish”,”complete”,”in”,”out”);

var word=words.unshift(“limit”,”lines”)

// the array words will be:

// limit, lines, finish, complete, in, out

JavaScript Objects
JavaScript is an Object-Oriented language. This means that it is capable of working with
objects. An object is an aggregate data type, a complex data type that is made up of a
collection of data elements.

If you are familiar with other Object-Oriented languages, then JavaScript objects should
not pose a problem. They do not work the same way that they do in C++ or Java, but the
similarities are more than enough to start with.

Objects

object: a composite data type that holds a collection of data elements than can be referenced by
name

Objects are composite data types. An object provides for the storage of multiple data
values in a single unit. Each value is assigned a name which may then be used to
reference it. Each element in an object is referred to as a property. Object properties can
be seen as an unordered list of name value pairs contained within the container object.

Object comes in two flavors. There are system defined objects, which are predefined
and come with the JavaScript parser or with the browser running the parser. And there are
user defined objects, which the programmer creates.

class: a definition, or description, of how the object is supposed to be created, what it contains,
and how its work

There are two important concepts to understand when talking about objects. These are
the ideas of class and instance.

Creating objects is a two step process. First you must define a class of objects, then
you use the object class by declaring instances of that class within the program. The object
class is a definition, or description, of how the object is supposed to be created, what it
contains, and how it works. The object instance is a composite data type, or object,
created based on the rules set forth in the class definition.
instance: a composite data type, or object, created based on the rules set forth in the class
definition

This break between class and instance is not new, it is just that before objects, all data
classes were hard coded into the parser and you could just make use of them while
creating variables that were instances of those classes. Someone, somewhere, had to write
the code to define the integer data type as being a numeric value with no fractional
component. Whenever you declare an integer variable, you make use of this definition to
create, or instantiate, an integer. Fortunately for us, it all happens behind the scenes.

The point of object-based programming languages is that they give the user the ability
to define their own data types that can be specifically tailored to the needs of the
application. There are still system-defined data types and object classes, so you don't need
to worry about defining commonly used types of variables, but you now can go beyond
them.

Since objects are composite data types, they can contain more than one piece of data.
In fact, the very point of the object is to bring together related data elements into a logical
grouping. This grouping can contain not only data values, but also rules for processing
those values. In an object, a data element is called a property, while the rules the object
contains for processing those values are called methods. This makes objects very

powerful because they can not only store data, but they can store the instructions on
what to do with that data.

The Generic Object

If you want to create an instance of an object that is not associated with any class,
you can do that too. The Object constructor allows you to declare a variable to be an
object, but not an instance of any particular class of object. You can then develop this
object in the code instead of declaring it up front.

// this creates an empty object

var bigNada = new Object( );

The Object class is the class that all objects are based on, including the ones you
define. Using the Object keyword to create an instance of an object creates a generic
object that has all the properities of an object, but no other special features.

Defining a specific named class creates an object class that differs from the default
Object class in the ways you specify. For instance the Date object class contains
predefined data fields, or properties that store information about the date and time as well
as methods for processing those values.

The point of having a generic object on which everything is built is to make coding
easier, so you don't have to tell the computer everything about how your object class
works, but just what its properties and methods are.
If that doesn't seem to make sense, think of it in terms of roads. If Road the
generic object defintion of all roads, then Thruway would be a class of Road. It has all the
properties of Road, plus a few specific to it. Route_90 would then be a specific instance of
Thruway. It contains all the properties of Thruway, as well as some values specific to it:
Route_90.start = 'Boston'. It even has some methods for processing values, for instance,
if (state == ('NY' or 'MA')) then tolls = true; else tolls = false;

Properties

To access object properties, you use the . operator. On the left of the period is the
name of the object and on the right the name of the property. For instance:

currBrowser = navigator.appName;

location.href = 'http://www.hvcc.edu';

When working with objects, the values are stored in the properties, not in the
object itself. The object is a container that is not meant to have any value in and of itself.
If you try to assign a value to the object itself you will overwrite the entire object with that
value. If you try to read directly from the object instead of from one of its properties, you
will generate an error.

If you assign a value to a property that does not exist, then JavaScript will create
that property and assign it to this instance of the object.

var holiday = new Object( );

// set some holidays

holiday.NewYears = 'January 1';

holiday.Halloween = 'October 21';

// you can also set properties as new object instances

holiday.Christmas = new Date('December 25');

If you try to read a property that does not exist, it will return undefined. Once you
have properties defined, you can either access them by name or use the for ... in
statement to enumerate them.

// This will write out 'January 1'

document.write(holiday.NewYears);

// This will write out all the holidays

for (hDate in holiday) {

document.write(holiday[hDate]);

}
Object Classes

In order to understand objects, it helps to know how to define your own object
classes. Remember that at the beginning of this set of tutorials I said it was a thin line
between objects and functions. That thin line is the keyword this. The this keyword refers
to the current function named and allows you to associate values with it. As an example,
let us work with a circle. In oder to define a circle, we need a center point and a radius.
We would define the circle object like this:

function Circle(x, y, r) {

this.xCoord = x;

this.yCoord = y;

this.radius = r;

this.circum = 2 * Math.PI * this.radius;

this.area = Math.PI * (this.radius * this.radius);

What have we done here? We have created an object class called circle with five
properties. The xCoordinates and yCoordinates of the center point, the radius, the
circumference and the area. Three of the parameters are taken directly from arguments
passed to the function, the other two are calculated from these values.

To create an instance of the class circle, you use the constructor function:

var littleCirc = new Circle(10, 10, 5);

After this statement we can now access the values of the circle we have just
defined by referring to the properties of this instance:

// this will write the x-coordinate for the circle

document.write(littleCirc.xCoord);

// this will write out the circumference for the circle

document.write(littleCirc.circum);

The calculated values are only calculated once, when the object is first
instantiated, or created. How do we modify the calculated values? Well, we could write a
function that does this every time, but we would have to write that function for every
program that used the Circles object.

There should be a way to associate such a function with the Circle object. And
there is. It is through the use of methods.

Object Methods
Method: a function associated with and invoked through an object

Methods are functions that are associated with and invoked through objects. Since
functions can be treated like variables in JavaScript, we can assign them to properties in
the object and refer to them in the same way.

Let's revise our Circle object. Note that since you can nest functions, I am going to
take advantage of this ability in order to better modularize our code.

function betterCircle(x, y, r) {

function comput_circum( ) {

return (2 * Math.PI * this.radius);

function comput_area( ) {

return (Math.PI * (this.radius * this.radius));

this.xCoord = x;

this.yCoord = y;

this.radius = r;

this.circum = comput_circum;

this.area = comput_area;

Note what I have done here. I am still using the this keyword inside the new
functions. This means that they need to have an instance of the object to act upon. I am
not passing them any values (although I could), instead I am using the keyword this to get
the required values from the object itself. Also, I have then replaced the computations in
the assignments for circumference and area with the function names. I can now invoke
them with this.circum( ); and this.area( );. The brackets are required now, since these
properties no longer contain numeric values, but functions that return numeric values.

JavaScript Object Hierarchy

Many JavaScript objects are contained within each other. JavaScript objects have a
container to contained object relationship rather than a class and subclass relationship.
Properties are not inherited from one type of object to another. There are two main types
of JavaScript objects.

• Language Objects - Objects provided by the language and are not dependent on
other objects.
• Navigator - Objects provided by the client browser. These objects are all sub
objects to the navigator object.

Beyond that, objects are those created by the programmer.

The "Language" box shown in the drawing is a little misleading. It is not an object,
but is used in the drawing to illustrate the grouping of the objects supported by the
JavaScript language. Other references to objects include:

• Parent

• Self

• Top

JavaScript String Object

But wait, aren't strings primitive data types?

Yes they are. But JavaScript has an object equivalent of each of the primitive data
types.

There are some functions that can be performed on the value of primitive data types
that just require that they be objects in order to work properly. JavaScript, without batting
an eyelash, calmly converts primitive data types into objects if it needs to, converting
them back to primitive data types when it is done so that you never need know that
anything happened. It is not a thing you should ever have to worry about, but it is worth
knowing about because the String object comes with certain methods that can be used to
perform various types of string processing.

The String object does have a constructor function and can be declared with it.

var aStr = new String('A string object');


However, JavaScript is flexible and you can declare a string with a simple assignment to

a string variable and JavaScript will still let you treat it as an object.

var bStr = 'A string variable';

Regardless of how the string is created, you can still use it as an object or as a
primitive data type. The standards fanatics may cringe at the lack of consistency, but it
has its uses.

Before looking at some on the String methods, it should be noted that a string can be
seen as an array of characters. As with arrays indexing starts with zero, so the character
index positions number zero through length minus one.

1 1 1 1 1

1 1 Index Position: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Characters: A s t r


i n g

v a r i a b l e

Much string manipulation involves such things as searching the string, replacing text,
deleting text, adding text. Since these require that you know the position where you are
performing this action, you need to know how strings are indexed.

JavaScript string object properties and methods

Properties

• Length - The number of characters in the string.

• prototype - For creating more properties

Methods

• anchor(anchorName) - A string is displayed as an anchor with the name


specified.

• big() - String is displayed in large format. (big tags)

o document.write("This is BIG text".big())

Is the same as:

<BIG>This is BIG text</BIG>

Producing:

This is BIG text

• blink() - String is displayed blinking. (blink tags)

o document.write("This is BLINKING text".blink())

Is the same as:


<BLINK>This is BLINKING text</BLINK>

Producing:

This is BLINKING text

• bold() - String is displayed in bold characters. (bold tags)

o document.write("This is BOLD text".bold())

Is the same as:

<B>This is BOLD text</B>

Producing:

This is BOLD text

• charAt(index) - Returns a string containing the character at the specified


location. The example returns the character "r".

myname = "George"

myname.charAt(3)

• fixed() - A string is displayed in Teletype format (teletype tags).

o document.write("This is TT text".fixed())

Is the same as:

<TT>This is TT text</TT>

Producing:

This is TT text

• fontcolor(color) - String is displayed in the specified color.

o document.write("This is RED text".fontcolor("red"))

Is the same as:

<FONT color="red">This is RED text</FONT>

Producing:

This is RED text

• fontsize(size) - String is displayed in the specified font from a value of 1 to 7.

o document.write("This is SIZE 5 text".fontsize(5))

Is the same as:

<FONT size="5">This is SIZE 5 text</FONT>

Producing:
This is SIZE 5 text

• indexOf(pattern) - Returns -1 if the value is not found and returns the index of
the first character of the first string matching the pattern in the string. The example will
return a value of 3.

o myname = "George"

o myname.indexOf("r")

• indexOf(pattern, index) - Returns -1 if the value is not found and returns the
index of the first character of the first string matching the pattern in the string. Searching
begins at the index value in the string.

• italics() - String is displayed using the italics tags.

o document.write("This is ITALICS text".italics())

Is the same as:

<I>This is ITALICS text</I>

Producing:

This is ITALICS text

• lastIndexOf(pattern) - Returns -1 if the value is not found and returns the index
of the first character of the last string matching the pattern in the string.

• lastIndexOf(pattern, index) - Returns -1 if the value is not found and returns


the index of the first character of the last string matching the pattern in the string.
Searching begins at the index value in the string. The example will return a value of 5.

o myname = "George"

o myname.lastIndexOf("e")

• link(href) - A string is displayed as a hypertext link.

o document.write("Computer Technology Documentation

Project".link("http://ctdp.tripod.com/"))

Is the same as:

<A HREF="http://ctdp.tripod.com/">Computer Technology Documentation Project</A>

Producing:

Computer Technology Documentation Project

• small() - String is displayed using the small tags.

o document.write("This is SMALL text".small())


Is the same as:

<SMALL>This is SMALL text</SMALL>

Producing:

This is SMALL text

• split(separator) - Splits a string into substrings based on the separator


character. In the below example an array called splitValues is created. The splitValues[0]
string will be "Day" and the splitValues[0] string will be "Monday".

o nvpair = new String("Day=Monday")

o splitValues=nvpair.split("=")

• strike() - String is displayed using the strikeout tags.

o document.write("This is STRIKEOUT text".strike())

Is the same as:

<STRIKE>This is STRIKEOUT text</STRIKE>

Producing:

This is STRIKEOUT text

• sub() - String is displayed using the subscript tags.

o document.write("This is SUBSCRIPT text".sub())

Is the same as:

<SUB>This is SUBSCRIPT text</SUB>

Producing:

This is SUBSCRIPT text

• substr(start, length) - Returns the string starting at the "start" index of the
string Continuing for the specified length of characters unless the end of the string is found
first. The example will return "org".

o mysite = "Comptechdoc.org"

o myname.substring(12, 3)

• substring(start, end) - Returns the string starting at the "start" index of the
string and ending at "end" index location, less one. The example will return "org".

o mysite = "Comptechdoc.org"

o myname.substring(12,15)

• sup() - String is displayed using the superscript tags.


o document.write("This is SUPERSCRIPT text".sup())

Is the same as:

<SUP>This is SUPERSCRIPT text</SUP>

Producing:

This is SUPERSCRIPT text

• toLowerCase() - Returns a copy of the string with all characters in lower case.

• toUpperCase() - Returns a copy of the string with all characters in upper case.

JavaScript Date Object

The Date object handles all date and time processing for JavaScript. We talk about the
Date object in detail elsewhere. For now we will just look at some basic features of the
Date object, just enough to get you up and running.

Epoch: January 1, 1970: the beginning of Unix time

First, you should know that the Date object stores both date and time. JavaScript
counts date and time in milliseconds from the very first millisecond of January 1, 1970.
This date by the way, is often referred to as the Epoch and is the date from which all Unix
time begins. When you request that JavaScript display the date and time, it uses this
number to return the required information.

There are four different ways to create an instance of the Date object at least that we
will talk about here).

var someDate = new Date( );

This creates a new instance of the Date object that contains the current date and time
at the instant the command was executed.

var someDate = new Date(1014744562000);

This defines the date in terms of the number of milliseconds since the beginning of
January 1, 1970. The number here is equal to roughly 12:30pm, on Tuesday, February 26,
2002.

var someDate = new Date('Tue Feb 26 12:29:22 EST 2002');

You can create a new date object with a string that represents the current date and
time. JavaScript is capable of parsing most normal date / time formats. So for instance,
you could write new Date('February 26 2002') or new Date('26 Feb 2002') or even new
Date ('2-26-2002'). Yes, in the latter instance, you could have a problem if the date is
something like 2-5-2002. Is that the 5th of February or the 2nd of May? It is February 5th,
but the important point is to be careful when specifying dates this way. Your best bet is to
always use the name of the month and the full four digit year. If you are interested,
writing 26-2-2002 will return February 2, 2004. Can you figure out why?
var someDate = new Date(2002,1,26,12,29,22,00);

Specify the date as a list of numbers. These numbers represent, in order:

the four digit year

the month

the day

the hour

the minute

the second

the millisecond

It is also important to note that the month in this example, having the value of '1' is
February, not January. JavaScript, just to be difficult, stores months in an array, with
index values of 0 (for January) to 11 (for December).

Date Object properties, methods.

Properties

• prototype - For creating more properties.

Methods:

• getDate() - Get the day of the month. It is returned as a value between 1 and 31.

o var curdate = new Date()

o var mday = curdate.getDate()

o document.write(mday + "<BR>")

The above code prints the day of the month.

• getDay() - Get the day of the week as a value from 0 to 6

o var curdate = new Date()

o var wday = curdate.getDate()

o document.write(wday + "<BR>")

The above code prints the day of the week.

• getHours() - The value returned is 0 through 23.

o var curdate = new Date()

o var hours = curdate.getHours()

o document.write(hours + "<BR>")
The above code prints the hours since midnight.

• getMinutes() - The value returned is 0 through 59.

o var curdate = new Date()

o var minutes = curdate.getMinutes()

o document.write(minutes + "<BR>")

The above code prints the minutes past the hour.

• getMonth() - Returns the month from the date object as a value from 0 through 11.

o var curdate = new Date()

o var month = curdate.getMonth()

o document.write(month + "<BR>")

The above code prints the numeric value of the month.

• getSeconds() - The value returned is 0 through 59.

o var curdate = new Date()

o var seconds = curdate.getSeconds()

o document.write(seconds + "<BR>")

The above code prints the seconds since the last minute.

• getTime() - The number of milliseconds since January 1, 1970. this function allows
you to manipulate the date object based on a millisecond value then convert it back to
the form you want. In the example below, it is used to set a future expiration time of a
cookie.

o var futdate = new Date()

o var expdate = futdate.getTime()

o expdate += 3600*1000 //expires in 1 hour(milliseconds)

o futdate.setTime(expdate)

• getTimeZoneOffset() - Time zone offset in hours which is the difference between


GMT and local time.

o var curdate = new Date()

o var offset = curdate.getTimeZoneOffset()

o document.write(offset + "<BR>")

The above code prints the number of hours different between your timezone and GMT.
This value may change with daylight savings time..
• getYear() - Returns the numeric four digit value of the year.

o var curdate = new Date()

o var year = curdate.getYear()

o document.write(year + "<BR>")

The above code prints the numeric value of the year which is currently 2000.

• parse() - The number of milliseconds after midnight January 1, 1970 till the given
date espressed as a string in the example which is IETF format.

o var curdate = "Wed, 18 Oct 2000 13:00:00 EST"

o var dt = Date.parse(curdate)

o document.write(dt + "<BR>")

• setDate(value) - Set the day of the month in the date object as a value from 1 to
31.

• setHours(value) - Set the hours in the date object with a value of 0 through 59.

• setMinutes(value) - Set the minutes in the date object with a value of 0 through
59.

• setMonth(value) - Set the month in the date object as a value of 0 through 11.

• setSeconds(value) - Set the seconds in the date object with a value of 0 through
59.

• setTime(value) - Sets time on the basis of number of milliseconds since January


1, 1970. The below example sets the date object to one hour in the future.

o var futdate = new Date()

o var expdate = futdate.getTime()

o expdate += 3600*1000 //expires in 1 hour(milliseconds)

o futdate.setTime(expdate)

• setYear(value) - Set the year in the date instance as a 4 digit numeric value.

• toGMTString() - Convert date to GMT format in a form similar to "Fri, 29 Sep 2000
06:23:54 GMT".

o var curdate = new Date()

o dstring = curdate.toGMTString()

o document.write(dstring + "<BR>" + curdate.toLocaleString() + "<BR>")


The above example produces:

Wed, 18 Oct 2000 18:08:11 UTC

10/18/2000 14:08:11

• toLocaleString() - Convert date to local time zone format. See the example, above.

• UTC() - Based on a comma delimited string, the number of milliseconds after


midnight January 1, 1970 GMT is returned. The syntax of the string is "year,
month, day [, hrs] [, min] [, sec]". An example is "2000, 9, 29, 5, 43, 0" for Sept
29, 2000 at 5:43:0. The string is considered to be GMT. The hours, minutes, and
seconds are optional.

o document.write(Date.UTC(2000, 9, 29, 5, 43, 0) + "


")

The above example produces:

972798180000

JavaScript Boolean Object

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or
false).

Boolean Object

The Boolean object is an object wrapper for a Boolean value.

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or
false).

We define a Boolean object with the new keyword. The following code line defines a
Boolean object called myBoolean:

var myBoolean=new Boolean()

Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined,
or NaN, the object is set to false. Otherwise it is true (even with the string "false")!

All the following lines of code create Boolean objects with an initial value of false:

var myBoolean=new Boolean()

var myBoolean=new Boolean(0)

var myBoolean=new Boolean(null)

var myBoolean=new Boolean("")

var myBoolean=new Boolean(false)


var myBoolean=new Boolean(NaN)

And all the following lines of code create Boolean objects with an initial value of true:

var myBoolean=new Boolean(true)

var myBoolean=new Boolean("true")

var myBoolean=new Boolean("false")

var myBoolean=new Boolean("Richard")

JavaScript Number object

Number Object Properties

• MAX_VALUE - The largest value that may be used in JavaScript.

o if (Math.exp(value1)<= Number.MAX_VALUE)

o exponenta(value1)

o else

o exponentb(value1)

• MIN_VALUE - The smallest value that may be used in JavaScript.

• NaN - Used to indicate a value is not a number. A number object may be set
to this value to indicate that it is not really a number.

if (Month < 1 || Month > 12) {

Month = Number.NaN

• NEGATIVE_INFINITY - The value returned if a negative overflow occurs. Any


numeric value divided by this is 0.

• POSITIVE_INFINITY - The value returned if a positive value overflow occurs.


Any numeric value divided by this is 0.

• Prototype - For creating more properties.

Number Object Methods

The number object must have an instance created in order to use it. The number object
has no specific functions. Built in functions that are associated with numbers include:

• eval() - A powerful function that evaluates string expressions. The example below
returns "26".
• var str = "6 + 20"

• document.write(eval(str))

• isNaN()

• parseFloat() - Used to convert a string to an floating point value. The example


will return a value of 212.3.

var value1 = parseInt("212.3")

• parseInt() - Used to convert a string to an integer value. The example will return
a value of 212.

var value1 = parseInt("212.3")

• toString()

• valueOf()

JavaScript Math Object

The Math object is really a function library organized as an object. It is used to store
methods that perform various mathematical functions. Almost all Math methods are class
methods and return a value of some sort.

The JavaScript math object can be invoked without creating an instance of it.

Properties

Properties are invoked by lines like "Math.PI".

• E - Euler's constant

• LN2 - Natural log of the value 2

• LN10 - Natural log of the value 10

• LOG2E - The base 2 log of euler's constant (e).

• LOG10E - The base 10 log of euler's constant (e).

• PI - 3.1428 - The number of radians in a 360 degree circle (there is no other circle
than a 360 degree circle) is 2 times PI.

• SQRT1_2 - The square root of one half.

• SQRT2 - The square root of 2.

Methods

Methods are invoked by lines like "Math.sin(1)".

• abs(a) - Returns the absolute value of a. The result value is 23 in the example
below.
resultval = Math.abs(-23)

• acos(a) - Returns the angle in radians that has a cosine of the passed value. The
value of "resultval" is 90 degrees.

resultval = (180/Math.PI) * Math.cos(0)

• asin(a) - Returns the angle in radians that has a sine of the passed value. The
value of "resultval" is 90 degrees.

resultval = (180/Math.PI) * Math.sin(1)

• atan(a) - Returns the angle in radians that has a tangent of the passed value. The
"resultval" will be almost 90 degrees.

resultval = (180/Math.PI) * Math.atan(100)

• atan2(x,y) - Returns the polar coordinate angle based on cartesion x and y


coordinates. The value is returned in radians. The "resultval" will be 45.

resultval = (180/Math.PI) * Math.atan2(1,1)

• ceil(x) - Rounds up the value of "a" to the next integer. If the value is a already
whole number, the return value will be the same as the passed value. The example returns
13.

resultval = Math.ceil(12.01)

• cos(a) - Returns the cosine of "a" specified in radians. To convert radians to


degrees, divide by 2*PI and multiply by 360. The example below returns the cosine of 90
degrees which is 0.

resultval = Math.cos(90 * Math.PI/180)

• exp(a) - Returns Euler's constant to the power of the passed argument. This is
the exponential power. The example below will return a number between 9 and 10.

resultval = Math.exp(3)

• floor(a) - Rounds the passed value down to the next lowest integer. If the passed
value is already an integer the returned value is the same as the passed value. The value
returned in the example is 8.

resultval = Math.floor(8.78)

• log(a) - This function is the opposite of "exp()" returning the natural log of the
passed value. In the below example, 3 is the result.

resultval = Math.log(Math.exp(3))

• max(a,b) - Returns the larger value of a or b. The variable "resultval" below


becomes
5.

resultval = Math.max(5, 3)

• min(a,b) - Returns the lower value of a or b. The variable "resultval" below


becomes

3.

resultval = Math.min(5, 3)

• pow(a,b) - Takes the value of a to the power b. In the example below the value 5
is multiplied times itself three times for a result of 125 which is placed in the variable
"resultval".

resultval = Math.pow(5, 3)

• random() - Returns a random number between 0 and 1. To generate a number


from

0 to 9:

i1 = Math.round(Math.random() * 3)

• round(a) - Returns the value of a to the nearest integer. If the values decimal
value is .5 or greater the next highest integer value is returned otherwise the next lowest
integer is returned. In the example below, 5 is returned.

resultval = Math.round(5.3)

• sin(a) - Returns the sine of "a" specified in radians. To convert radians to


degrees, divide by 2*PI and multiply by 360. The example below returns the sine of 90
degrees which is 1.

resultval = Math.sin(90 * Math.PI/180)

• sqrt(a) - Returns the square root of a. the value of "resultval" is 5.

resultval = Math.sqrt(25)

• tan(a) - Returns the tangent of a value in radians which is the value of the sine
divided by the cosine.

resultval = Math.tan(0)
JavaScript Browser Detection

The JavaScript Navigator object contains information about the visitor's browser.

Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers.


However, there are some things that just don't work on certain browsers - specially on
older browsers.

So, sometimes it can be very useful to detect the visitor's browser type and
version, and then serve up the appropriate information.

The best way to do this is to make your web pages smart enough to look one way
to some browsers and another way to other browsers.

JavaScript includes an object called the Navigator object, that can be used for this
purpose.

The Navigator object contains information about the visitor's browser name,
browser version, and more.

The Navigator Object

The JavaScript Navigator object contains all information about the visitor's browser. We
are going to look at two properties of the Navigator object:

• appName - holds the name of the browser

• appVersion - holds, among other things, the version of the browser

Most Navigator objects have corresponding HTML tags. Refer to the appropriate object
section for more information.

• MimeType - Allows access to information about MIME types supported by the


browser.

• plugin - Access to information about all plugins the browser supports. <EMBED>

• window - The browser frame or window.

o frame- Allows access to all frames in the window. <FRAME>

o history - The URLs previously accessed in a window.

o location - Represents a URL.

o document - The HTML document loaded in the window. <BODY>

 anchor object anchors array - Allows access to all anchors in the


document. <A NAME="">

 applet - Allows access to all applets in the document.


 area - Allows access to an area in a client image map. <MAP>

 image object images array - Allows access to all images in the


document. <IMG>

 link object links array - Allows access to all links in the document.
<A HREF="">

 layer - Allows access to HTML layers.

 forms - Allows access to all forms in the document. <FORM>

• button - Allows access to a form button exclusive of a


submit or reset button. <INPUT TYPE="button">

• checkbox - Allows access to a formcheckbox. <INPUT


TYPE="checkbox">

• element - Allows access to buttons or fields in a form.

• FileUpLoad - Allows access to a form file upload element.


<INPUT TYPE="file">

• hidden - Allows access to a form hidden field. <INPUT


TYPE="hidden">

• option

• password - Allows access to a form password field. <INPUT


TYPE="password">

• radio - Allows access to a form radio button set. <INPUT


TYPE="radio">

• reset - Allows access to a form reset button.. <INPUT


TYPE="reset">

• select - Allows access to a form selected list with the option


allowing access to selected elements in the select list.
<SELECT>

• submit - Allows access to a form submit button. <INPUT


TYPE="submit">

• text - Allows access to a form text field. <INPUT


TYPE="text">

• textarea - Allows access to a form text area field.


<TEXTAREA>

• embeds - Allows access to embedded plug ins.

Example
<html>

<body>

<script type="text/javascript">

var browser=navigator.appName

var b_version=navigator.appVersion

var version=parseFloat(b_version)

document.write("Browser name: "+ browser)

document.write("<br/>")

document.write("Browser version: "+ version)

</script>

</body>

</html>

The variable browser in the example above holds the name of the browser, i.e.
"Netscape" or "Microsoft Internet Explorer".

The appVersion property in the example above returns a string that contains much
more information than just the version number, but for now we are only interested in the
version number. To pull the version number out of the string we are using a function called
parseFloat(), which pulls the first thing that looks like a decimal number out of a string and
returns it.

IMPORTANT! The version number is WRONG in IE 5.0 or later! Microsoft start the
appVersion string with the numbers 4.0. in IE 5.0 and IE 6.0!!! Why did they do that???
However, JavaScript is the same in IE6, IE5 and IE4, so for most scripts it is ok.

Example

The script below displays a different alert, depending on the visitor's browser:

<html>

<head>

<script type="text/javascript">

function detectBrowser()

var browser=navigator.appName
var b_version=navigator.appVersion

var version=parseFloat(b_version)

if ((browser=="Netscape"||browser=="Microsoft Internet Explorer")

&& (version>=4))

{alert("Your browser is good enough!")}

else

{alert("It's time to upgrade your browser!")}

</script>

</head>

<body onload="detectBrowser()">

</body>

</html>

Events:
By using JavaScript, we have the ability to create dynamic web pages. Events are
actions that can be detected by JavaScript.

Every element on a web page has certain events which can trigger JavaScript functions.
For example, we can use the onClick event of a button element to indicate that a function
will run when a user clicks on the button. We define the events in the HTML tags.

Event Handlers

To allow you to run your bits of code when these events occur, JavaScript provides
us with event handlers. All the event handlers in JavaScript start with the word on, and
each event handler deals with a certain type of event. Here's a list of all the event handlers
in JavaScript, along with the objects they apply to and the events that trigger them:

Event
Applies To: Triggered When:
Handler

onAbort Image The loading of the image is


cancelled.

onBlur Button, Checkbox, FileUpload, Layer, The object in question loses


Password, Radio, Reset, Select, Submit, focus (e.g. by clicking outside it
Text, TextArea, Window or pressing the TAB key).
onChange FileUpload, Select, Text, TextArea The data in the form element
is changed by the user.

onClick Button, Document, Checkbox, Link, Radio, The object is clicked on.
Reset, Submit

onDblClick Document, Link The object is double-clicked


on.

onDragDrop Window An icon is dragged and


dropped into the browser.

onError Image, Window A JavaScript error occurs.

onFocus Button, Checkbox, FileUpload, Layer, The object in question gains


Password, Radio, Reset, Select, Submit, focus (e.g. by clicking on it or
Text, TextArea, Window pressing the TAB key).

onKeyDown Document, Image, Link, TextArea The user presses a key.

onKeyPress Document, Image, Link, TextArea The user presses or holds


down a key.

onKeyUp Document, Image, Link, TextArea The user releases a key.

onLoad Image, Window The whole page has finished


loading.

onMouseDown Button, Document, Link The user presses a mouse


button.

onMouseMove None The user moves the mouse.

onMouseOut Image (NOT NS4), Link The user moves the mouse
away from the object.

onMouseOver Image (NOT NS4), Link The user moves the mouse
over the object.

onMouseUp Button, Document, Link The user releases a mouse


button.

onMove Window The user moves the browser


window or frame.

onReset Form The user clicks the form's


Reset button.

onResize Window The user resizes the browser


window or frame.

onSelect Text, Textarea The user selects text within


the field.

onSubmit Form The user clicks the form's


Submit button.

onUnload Window The user leaves the page.

Using an Event Handler

To use an event handler, you usually place the event handler name within the
HTML tag of the object you want to work with, followed by ="SomeJavaScriptCode",
where SomeJavaScriptCode is the JavaScript you would like to execute when the event
occurs.
For example:

<input type="submit" name="clickme" value="Click Me!" onClick="alert('Thank You!')">

The Event Object

The Event object is created automatically whenever an event occurs. There are a
number of properties associated with the Event object that can be queried to provide
additional information about the event:

Event
Description
Property

event.data Used by the onDragDrop event. Returns an array of URL's of dropped objects.

event.height Stores the height of the window or frame containing the object connected
with the event.

event.modifi Returns a string listing any modifier keys that were held down during a key or
ers mouse event. The modifier key values are: ALT_MASK, CONTROL_MASK,
SHIFT_MASK and META_MASK.

event.pageX These properties hold the X and Y pixel coordinates of the cursor relative to
event.pageY the page, at the time of the event.

event.screen These properties hold the X and Y pixel coordinates of the cursor relative to
X the page, at the time of the event.
event.screenY

event.target Returns a string representing the object that initiated the event.

event.type Returns a string representing the type of the event (keypress, click, etc).

event.which Returns a number representing the mouse button that was pressed (1=left,
2=middle, 3=right) or the ASCII code of the key that was pressed.

event.width Stores the width of the window or frame containing the object connected
with the event.

event.x These properties hold the X and Y pixel coordinates of the cursor relative to
event.y the layer connected with the event or, for the onResize event, the width and
height of the object after it was resized. (You can also use event.layerX and
event.layerY, which do the same thing.)

SrcElement The element that fired the event

returnValue Determines whether the event is cancelled

cancelBubbl
Can cancel an event bubble
e

clientX Mouse pointer X coordinate relative to window

clientY Mouse pointer Y coordinate relative to window

offsetX Mouse pointer X coordinate relative to element that fired the event

offsetY Mouse pointer Y coordinate relative to element that fired the event

altKey True if the alt key was also pressed

ctrlKey True if the ctrl key was also pressed

shiftKey True if the shift key was also pressed


keyCode Returns UniCode value of key pressed

onChange

onChange is commonly used to validate form fields or to otherwise perform an


action when a form field's value has been altered by the user. The event handler is
triggered when the user changes the field then clicks outside the field or uses the TAB key
(i.e. the object loses focus).

Example

This example code ensures that you type in both your first and your last names. It will
bring up an alert box and refocus the text box field if you only type one word into the text
box.

Please enter your name: <input type="text"

name="your_name" onChange=validateField(this)>

<script language="JavaScript">

function validateField ( fieldname )

if ( ( fieldname.value ) &&

( ! fieldname.value.match ( " " ) ) )

alert ( "Please enter your first and last names!" );

fieldname.focus ( );

</script>

onClick

The onClick handler is executed when the user clicks with the mouse on the
object in question. Because you can use it on many types of objects, from buttons through
to checkboxes through to links, it's a great way to create interactive Web pages based on
JavaScript.

Example

In this example, an alert box is displayed when you click on the link below.

<a href="#" onClick="alert('Thanks!')">Click Me!</a>


onFocus

onFocus is executed whenever the specified object gains focus. This usually
happens when the user clicks on the object with the mouse button, or moves to the object
using the TAB key. onFocus can be used on most form elements.

Example

This example text box contains the prompt Please enter your email address that is
cleared once the text box has focus.

<input type="text" name="email_address"

size="40" value="Please enter your email address"

onFocus="this.value=''">

onKeyPress

You can use onKeyPress to determine when a key on the keyboard has been
pressed. This is useful for allowing keyboard shortcuts in your forms and for providing
interactivity and games.

Example

This example uses the onKeyPress event handler for the Window object to
determine when a key was pressed. In addition, it uses the which property of the Event
object to determine the ASCII code of the key that was pressed, and then displays the
pressed key in a text box. If event.which is undefined it uses event.keyCode instead
(Internet Explorer uses event.keyCode instead of event.which).

1. <html>

2. <body onKeyPress = "show_key(event.which)">

3. <form method="post" name="my_form">

4. The key you pressed was:

5. <input type="text" name="key_display" size="2">

6. </form>

7. <script language="JavaScript">

8. function show_key ( the_key )

9. {
10. if ( ! the_key )

11. {

12. the_key = event.keyCode;

13. }

14. document.my_form.key_display.value = String.fromCharCode ( the_key );

15. }

16. </script>

17. </body>

18. </html>

onLoad

The onLoad event handler is triggered when the page has finished loading.
Common uses of onLoad include the dreaded pop-up advertisement windows, and to start
other actions such as animations or timers once the whole page has finished loading.

Example

This simple example displays an alert box when the page has finished loading:

<html>

<body onLoad = "alert('Thanks for visiting my page!')">

My Page

</body>

</html>

onMouseOut, onMouseOver

The classic use of these two event handlers is for JavaScript rollover images
(images, such as buttons, that change when you move your mouse over them).

Here's a simple example that alters the value of a text box depending on whether the
mouse pointer is over a link or not.

<form>

<input type="text" name="status" value="Not Over the Link">


<br>

<a href="" onMouseOver="status.value='Over the Link'"

onMouseOut="status.value='Not Over the Link'">Move

the Mouse Over Me!</a>

</form>

onSubmit

The onSubmit event handler, which works only with the Form object, is
commonly used to validate the form before it's sent to the server.

Example

This example asks you to confirm whether you want to submit the form or not
when you click on the button. It returns true to the event handler if the form is to be
submiited, and false if the submission is to be cancelled.

<form onSubmit="return confirm('Are You Sure?')">

<input type="submit" name="submit" value="Submit">

</form>

Event Bubbling

Event bubbling is another advanced event handling technique.

This means that any event handlers we have defined for these higher-level objects
are also activated.

To see this in action, we shall look at a form that demonstrates event bubbling.

<HTML>

<HEAD>

<TITLE>EventBubbling</TITLE>

</HEAD>

<BODY onclick="alert('<BODY>');">

<FORM NAME="MAINFORM" style="background-color:yellow" onclick="alert('MAINFORM');">

<INPUT TYPE="TEXT" NAME="TEXT1" onclick="alert('TEXT1');">Name

<BR>

<INPUT TYPE="RADIO" NAME="R1" VALUE="RADIO1" onclick="alert('RADIO1');">Male

<BR>

<INPUT TYPE="RADIO" NAME="R1" VALUE="RADIO2" onclick="alert('RADIO2');">Female


</FORM>

</BODY>

</HTML>

Depending on where you click on the form you will get a different sequence of
alerts.

As each element in our example has an onclick event handler, when we click a
form element, the event activates:

(radio1, onclick)
(mainform, onclick)
(body, onclick)

If we just click the form, we only activate:

(mainform, onclick)

(body, onclick)

And if we only click the body, we only activate:

(body, onclick)

If these event handlers are not defined, then no action is taken. So, if (mainform,
onclick) does not exist, then nothing would happen and the event would pass through
mainform and continue onto the body.

We can also stop the event bubble, using event.cancelBubble.

event.cancelBubble

event.cancelBubble is very similar to cancelling events. We are allowed to


'burst' the bubble, and prevent it from carrying on up the ownership tree.

We can do this at any stage, and the event bubble will no longer exist.

Adapting the previous code, change the text box line of code to:

<INPUT TYPE="TEXT" NAME="TEXT1"


onclick="alert('TEXT1');event.cancelBubble=true;">Name

We can use event bubbling to provide complex interactivity with a web page - we
may have several functions all firing because of event bubbling. Imagine two <DIV>
elements, one inside the other. We could use the event bubble to pass any event from the
inner <DIV> element to the outer <DIV> element.

Or we can group elements together, which is useful if we have a lot of elements


that use the same event handler. Instead of writing an event handler for every element,
we can write one event handler for a containing element, and use the principle of event
bubbling to pass any events to the containing element, which knows what to do.

Filters and Transitions:


Filters: Applying Filters to text and images causes changes that are persistent.

Transitions: Applying a transition allows you to transfer from one page to another with
a pleasant visual effect such as random dissolve.

Each of the visual effects achievable with filters and transitions is programmable,
so these effects may be adjusted dynamically by programs that respond to user-initiated
events like mouse clicks and keystrokes.

Part of the beauty of DHTML filters and transitions is that they are built right into
Internet Explorer. Filters and transitions are included with the CSS filter property. They
give you the same kind of graphics capabilities you get through presentation software like
Microsoft’s Power Point.

Filters and transitions can be applied to block-level elements such as DIV or P,


and can only be applied to inline-level elements such as STRONG or EM if the element has
its height or width CSS properties set.

Filters:

Flip filters: flipv and fliph

Fundamental filters supported by Dynamic HTML are filpv and fliph popularly known as
flip filters. These filters create mirror effects for the images or text. These are vertical in
nature if filter is flipv and horizontal in the case of fliph.

In dynamic HTML creation of filter is very simple. Only thing you require is style
sheets. In styles, you have a special style that is filter style, which for all the kinds of
filters. The value passed to filter is fliph for horizontal flip and flipv for vertical flip. If you
require both filters just apply both of them.

Ex: style= “filter:fliph” for horizontal

style=”filter:flipv” for vertical

style=”filter:fliph flipv” for both flips.

Simple program on filters as follows

37. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

38. <HTML>

39. <!-- Fig. 1: flip.html -->

40. <!-- Using the flip filters -->


41. <HEAD>

42. <TITLE>the flip filter</TITLE>

43.

44. <STYLE TYPE = "text/css">

45. BODY { background-color: #CCFFCC }

46. TABLE { font-size: 3em;

47. font-family: Arial, sans-serif;

48. background-color: #FFCCCC;

49. border-style: ridge ;

50. border-collapse: collapse }

51. TD { border-style: groove;

52. padding: 1ex }

53. </STYLE>

54. </HEAD>

55. <BODY>

56. <TABLE>

57. <TR>

58. <!-- Filters are applied in style declarations -->

59. <TD STYLE = "filter: fliph">Text</TD>

60. <TD>Text</TD>

61. </TR>

62. <TR>

63. <!-- More than one filter can be applied at once -->

64. <TD STYLE = "filter: flipv fliph">Text</TD>

65. <TD STYLE = "filter: flipv">Text</TD>

66. </TR>
67. </TABLE>

68. </BODY>

69. </HTML>

Output:

Transparency with the Chroma Filter:

The chroma filter allows you to apply transparency effects dynamically, without
using a graphics editor to hard-code transparency into the image. In style argument if you
pass filter: chroma, then chroma filter starts it’s processing. By dynamic features, if you
can use any type of graphical user components to apply this feature. By using
identification of an image you can call filters collection and change its properties as follows.

chImg.filters(“chroma”).color=color code;

Ex:

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

2. <HTML>

3. <!-- Fig 2: chroma.html -->

4. <!-- Applying transparency using the chroma filter -->

5. <HEAD>

6. <TITLE>chroma filter</TITLE>

7. <SCRIPT LANGUAGE = "JavaScript">

8. function changecolor()

9. {
10. if ( colorSelect.value ) { // if the user selected a color,

11. // parse the value to hex and set the filter color.

12. chromaImg.filters( "chroma" ).color = parseInt( colorSelect.value, 16 );

13. chromaImg.filters( "chroma" ).enabled = true;

14. }

15. else // if the user selected "None",

16. // disable the filter

17. chromaImg.filters( "chroma" ).enabled = false;

18. </SCRIPT>

19. </HEAD>

20. <BODY>

21. <H1> chroma filter </H1>

22. <IMG ID=”chromaImg” SRC=”trans.gif” STYLE=”position: absolute; filter: chroma” >

23. <!—the ONCHANGE event fires when a selection is changed - - >

24. <SELECT ID= “colorSelect” ONCHANGE= “changecolor()”>

25. <OPTION VALUE= “ “> None

26. <OPTION VALUE= “ 00FFFF“> Cyan

27. <OPTION VALUE= “ FFFF00 “> Yellow

28. <OPTION VALUE= “FF00FF “> Magenta

29. <OPTION VALUE= “000000 “ SELECTED> Black

30. </SELECT>

31. </BODY>

32. </HTML>

Output:
Masking:

Applying the mask filter to an image allows you to create an image mask, in
which the background of an element is a solid color and the foreground of an element is
transparent to the image or color behind it.

These effects can be achieved in DHTML by using following statements.

<h1 style= “position: absolute; top:95; left:234; filter: mask(color=#000000)”>

Followed by an image behind this header so that you can get the mask feel.

<img src=”flower.jpg” width=”400” height=”200”>

Better to get both are placed at one location

Ex:
1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
2. <HTML>
3. <!-- Fig 3: mask.html -->
4. <!-- Placing a mask over an image -->
5. <HEAD>
6. <TITLE>Mask filter</TITLE>
7. </HEAD>
8. <BODY>
9. <H1>Mask Filter</H1>
10. <!-- Filter parameters are specified in parentheses, in -->
11. <! -- The form param1 = value1, param2 = value2, etc. -->
12. <DIV STYLE = "position: absolute; top: 125; left: 20;
13. filter: mask( color = #CCFFFF )">
14. <H1 STYLE = "font-family: Courier, monospace">
15. AaBbCcDdEeFfGgHhIiJj<BR>
16. KkLlMmNnOoPpQqRrSsTt
17. </H1>
18. </DIV>
19. <IMG SRC = "gradient.gif" WIDTH = "400" HEIGHT = "200">
20. </BODY>
21. </HTML>

Output:

Miscellaneous Image Filters: invert, gray and xray

The following three filters apply simple image effects to image or text. The invert
filter applies a negative image effect- dark area become light and light areas become dark.
The gray filter applies a grayscale image effect, in which all color is stripped from the
image and all that remains is brightness data. The xray filter applies an xray effect, which
is basically just an inversion of the grayscale effect.

Ex:
1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0

2. <HTML>

3. <!-- Fig 4: misc.html -->

4. <!—image filters to invert, gray and xray an image -->

5. <HEAD>

6. <TITLE>misc filters</TITLE>

7. <STYLE TYPE=”text/CSS”>

8. cap { font-weight: bold;

background-color: #DDDDAA;

text-align: center}

9. </STYLE>

10. </HEAD>

11. <BODY>

12. <TABLE>

13. <TR CLASS=”cap”>

14. <TD> Normal </TD>

15. <TD> Gray Scale </TD>

16. <TD> X ray</TD>

17. <TD> Invert </TD>

18. </TR>

19. </TABLE>

20. </BODY>

21. </HTML>

Output:

Adding Shadows to Text:

A simple filter that adds depth to your text is the shadow filter. This filter creates a
shadowing effect that gives your text a three-dimensional look.
Syntax:

Filter: shadow (direction=50, color=black)

– Properties are direction and color. Property direction is direction of


shadow

• 0 (up), 45 (above-right), 90 (right), 135 (below-right), 180


(below), 225 (below-left), 270 (left) and 315 (above-left)

– Property color is color of a shadow

Ex:
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<HTML>
3
4<!-- Fig 17.5: shadow.html -->
5<!-- Applying the shadow filter -->
6
7<HEAD>
8<TITLE>Shadow Filter</TITLE>
9
10<SCRIPT LANGUAGE = "JavaScript">
11 var shadowDirection = 0;
12
13 function start()
14 {
15 window.setInterval( "runDemo()", 500 );
16 }
17
18 function runDemo()
19 {
20 shadowText.innerText =
21 "Shadow Direction: " + shadowDirection % 360;
22 shadowText.filters( "shadow" ).direction =
23 ( shadowDirection % 360 );
24 shadowDirection += 45;
25 }
26</SCRIPT>
27</HEAD>
28
29<BODY ONLOAD = "start()">
30
31<H1 ID = "shadowText" STYLE = "position: absolute; top: 50;
32 left: 50; padding: 10; filter: shadow( direction = 0,
33 color = red )">Shadow Direction: 0</H1>
34</BODY>

35</HTML>
Output:

Gradient Effects:

One of beautiful effect of image graphics is to display an image starting with a


color and ending with complete picture. This can be called as gradient effects. The alpha
filter is used to create the above said gradient effect. Alpha filter as follows

Filter: alpha ( style=2, opacity=100, finishopacity=0)”>

It takes three important parameters, the style parameter indicates how the gradient
transforms, there are four options are available for this.

0- Uniform

1- Linear

2- Circular

3- Rectangular

Other two parameters are opacity indicates the percentage at which percent opacity the
specified gradient starts, and other one finishopacity indicates where it finishes.

Glow Text:

Shadow is display a shadow color to given text. Filters provides another facility that
adds colors for all sides of a text, some times it is called aura color around given text. This
filter is called as glow filter. It provides both facilities color and strength of display.

For example if you give

Filter: glow (color= blue; strength=8);


It adds blue color around the given text with strength factor of 8.

If you want to add a filter to h1 then

<h1 id= “glow” style=”position: absolute; filter: glow(color=blue,


strength=8); font-size:4em”>

Web design

This statement adds blue color around web design text.

Transitions:

DHTML advanced filters; transitions are allowed Power Point kind of features to
your text or image. A smooth fade-in and fade-out effect you can get by using blend
Trans. When you want transitions to your web page, there are three steps for applying it.

First step is, initializing for which element you want to apply transition with the
help of apply() method. For example

transText. Filters (“blendTrans”).aplly();

Second step is , decide what is the target to make the text, means source to
visible or source to hidden by using

transText.style.visibility=”hidden”;

Last step is, start transition. It done through play() method.

transText.filters(“blendTrans”).Play();

Você também pode gostar