You are on page 1of 78

Introduction to JavaScript

JavaScript is a programming language that can be included on web pages to make them

more interactive. You can use it to check or modify the contents of forms, change images,

open new windows and write dynamic page content. You can even use it with CSS to

make DHTML (Dynamic Hypertext Markup Language). This allows you to make parts

of your web pages appear or disappear or move around on the page. JavaScripts only

execute on the page(s) that are on your browser window at any set time. When the user

stops viewing that page, any scripts that were running on it are immediately stopped. The

only exception is a cookie, which can be used by many pages to pass information

between them, even after the pages have been closed.

Before we go any further, let me say; JavaScript has nothing to do with Java. If we are

honest, JavaScript, originally nicknamed Livewire and then Live Script when it was

created by Netscape, should in fact be called ECMAscript as it was renamed when

Netscape passed it to the ECMA for standardization.

JavaScript is a client side, interpreted, object oriented, high level scripting language,

while Java is a client side, compiled, object oriented high level language. Now after that

mouthful, here's what it means.

Client side

Programs are passed to the computer that the browser is on, and that computer

runs them. The alternative is server side, where the program is run on the server
and only the results are passed to the computer that the browser is on. Examples

of this would be PHP, Perl, ASP, JSP etc.

Interpreted

The program is passed as source code with all the programming language visible.

It is then converted into machine code as it is being used. Compiled languages are

converted into machine code first then passed around, so you never get to see the

original programming language. Java is actually dual half compiled, meaning it is

half compiled (to 'byte code') before it is passed, then executed in a virtual

machine which converts it to fully compiled code just before use, in order to

execute it on the computer's processor. Interpreted languages are generally less

fussy about syntax and if you have made mistakes in a part they never use, the

mistake usually will not cause you any problems.

Scripting

This is a little harder to define. Scripting languages are often used for performing

repetitive tasks. Although they may be complete programming languages, they do

not usually go into the depths of complex programs, such as thread and memory

management. They may use another program to do the work and simply tell it

what to do. They often do not create their own user interfaces, and instead will

rely on the other programs to create an interface for them. This is quite accurate

for JavaScript. We do not have to tell the browser exactly what to put on the

screen for every pixel, we just tell it that we want it to change the document, and

it does it. The browser will also take care of the memory management and thread

management, leaving JavaScript free to get on with the things it wants to do.
High level

Written in words that are as close to english as possible. The contrast would be

with assembly code, where each command can be directly translated into machine

code.

Object oriented

See the section on 'object oriented programming' for details.

How is JavaScript constructed

The basic part of a script is a variable, literal or object. A variable is a word that

represents a piece of text, a number, a boolean true or false value or an object. A literal is

the actual number or piece of text or boolean value that the variable represents. An object

is a collection of variables held together by a parent variable, or a document component.

The next most important part of a script is an operator. Operators assign literal values to

variables or say what type of tests to perform.

The next most important part of a script is a control structure. Control structures say what

scripts should be run if a test is satisfied.

Functions collect control structures, actions and assignments together and can be told to

run those pieces of script as and when necessary.

The most obvious parts of a script are the actions it performs. Some of these are done

with operators but most are done using methods. Methods are a special kind of function

and may do things like submitting forms, writing pages or displaying messages.
Events can be used to detect actions, usually created by the user, such as moving or

clicking the mouse, pressing a key or resetting a form. When triggered, events can be

used to run functions.

Lastly and not quite so obvious is referencing. This is about working out what to write to

access the contents of objects or even the objects themselves.

As an example, think of the following situation. A person clicks a submit button on a

form. When they click the button, we want to check if they have filled out their name in a

text box and if they have, we want to submit the form. So, we tell the form to detect the

submit event. When the event is triggered, we tell it to run the function that holds

together the tests and actions. The function contains a control structure that uses a

comparison operator to test the text box to see that it is not empty. Of course we have to

work out how to reference the text box first. The text box is an object. One of the

variables it holds is the text that is written in the text box. The text written in it is a literal.

If the text box is not empty, a method is used that submits the form.

The early Internet and the first generation browsers

Proposed in 1962, the Internet was created in 1969, known then as the ARPANET, by the

Advanced Research Projects Agency (ARPA), linking their four main computers in their

four research headquarters in Southwest USA. It had been four years since 1965, when

they had first managed to connect two computers over the telephone system. By 1972,

many computers in universities across the USA had been connected, and the email,

newsgroup and telnet protocols were being developed. Many further internet protocols
were developed in the 1970s and 1980s, such as FTP and Gopher, and the underlying

TCP/IP protocol replaced the original NCP protocol in the early 1980s. And so the

ARPANET became the Internet, a network of university and military computers

connected to each other via many other computers, communicating using the TCP/IP

protocol. The idea was that, even if the Cold War became real, and portions of the

Internet were damaged by nuclear war, the remaining links could take over so the internet

could still function.

The World Wide Web (which basically means using the HTTP protocol to retrieve

hyperlinked documents) was proposed in March 1989 by Tim Berners-Lee, a British

computer specialist, at the European Laboratory for Particle Physics (CERN) for Swiss

scientists, so that they could easily publish and share their research with the 12 nations of

the high-energy physics community. He created the world's first browser, named

'Worldwide Web', in 1990, and released it in 1991. In 1992, browsers became a

worldwide tool for transmission of text-based information, using the HTTP protocol. In

1993 the NCSA mosaic browser was created and offered the opportunity to use inline

images, and colors and hyperlinks as well as plain text. It was also the first browser to run

in a graphical interface environment. The first version of Netscape was released in 1994,

written by a breakaway group from the original Mosaic team.

JavaScript is born - the second and third generations

Netscape 2 was released in early 1996 and offered completely new technologies created

by the Netscape group, the most important of which were frames and JavaScript.
JavaScript was a programming language written by Brendan Eich that was able to be

embedded in Web pages and could process numbers and modify the contents of forms.

While in development, JavaScript had been known as Mocha then LiveWire then

LiveScript. Its core script syntax closely resembled Java, so it was renamed JavaScript

when it was released. The way it referenced forms, links and anchors as children of the

document object, and inputs as children of their parent form became known as the DOM

level 0.

The same year, Netscape passed their JavaScript language to the European Computer

Manufacturers Association (ECMA) for standardisation. The ECMA produced the

ECMAscript standard, which embodied the JavaScript core syntax, but did not specify all

aspects of the DOM level 0. With the release of Netscape 3 later in the same year,

Netscape had produced JavaScript 1.1, which could also change the location of images,

bringing on a wave of Web sites that used this most popular of Web page effects, making

images change when the mouse passed over them. The images were also referenced as

children of the document object and thus the DOM level 0 was completed.

DHTML - the forth generation

ECMAscript was still updated, as with the release of Netscape 4 in 1997, Netscape

produced their most advanced technology to date, DHTML. Using a combination of yet

more proprietary HTML tags and portions of the new W3C CSS 1 recomendation,

JavaScript 1.2 gave programmers the ability to change the CSS style for document

components, in particular the position and visibility of elements on the page, which were
adopted by the W3C for their CSS 2 specification. This layers technology was greatly

accepted, although little used because of its lack of support for older, and still popular

browsers. JavaScript now offered the {} and [] syntaxes for creating objects and arrays

but more importantly, the Layers DOM was born.

As layers became more popular, Microsoft decided to muscle in on the competition,

releasing their Internet Explorer 4 browser in 1997. This browser showed programmers

just how agile a browser could be. Unlike the Layers DOM model, the proprietary DOM

model of IE 4 allowed any part of the document to be referenced, and have any CSS style

changed, including many CSS 2 declarations. Most could have their contents rewritten. It

also offered many other extensions, such as filters and transitions. This new syntax for

referencing document components was more reliable and far more versitile and the W3C

decided to adopt many of its syntaxes and components for their forthcoming DOM

recommendation.

In mid 1998, Netscape released a new version of their browser, still relying on the poor

layers DOM. They had failed to fix many of the bugs that plagued their browser, despite

the new JavaScript 1.3 version. They also released the source code, and stopped charging

for their browser. They had hoped to produce the next version of their browser using the

open source community. The open source community had more sense, and decided

instead to abandon the unstable and restricted Netscape core, in favour of completely re-

writing, according to the W3C DOM guidelines.

W3C DOM - the fifth generation


In 1999, Microsoft released the most advanced browser so far, Internet Explorer 5, the

first fifth generation browser, which supported a large amount of the W3C DOM 1

recommendation, as well as the properietary techniques used by Internet Explorer 4. It

also supported what is the current version of ECMAscript, ECMAscript 3, equivalent to

JavaScript 1.5 (JavaScript 1.4 was used only by Netscape's server side JavaScript). As

with all Internet Explorer versions, it still used a JavaScript version with several core

extensions, known as JScript.

The W3C DOM allowed much greater functionality than the previous DOMs. It gave

ways to create, remove and modify html elements, even after the page had loaded. All

aspects of the page could be changed. Attributes could be added and removed from

HTML elements. All styles could be changed, added or removed. It even changed the

way that events could be detected, allowing more than one handler function for any

event, capturing and bubbling were both supported. Internet Explorer still does not

support all of these event techniques according to the standard, and instead uses

proprietary variations. The W3C DOM also represented the document differently, as a

tree structure where the root was the HTML element, and each element within it was a

child object of the element it was contained within. Text within elements was a child

node of the parent element node. This gave a much more complex but realistic

representation of the document, that gave access to every part of it.

In 2000 Opera released their Opera 4 browser, one of the most badly bugged to date. Its

new script handling was based on the W3C DOM, although it only implemented enough

to be comparable to Intenet Explorer 4. However, its bugs usually caused it to fail to


manage even that. With the subsequent Opera 5 and 6 releases, the functionality did not

increase, but the stability and popularity definitely did. At about the same time, several

other browser projects came to light, such as Konqueror, and ICEbrowser, both of which

were fifth generation. Television browsers were also becoming fifth generation.

A new breed

In 2002, the Mozilla project finally released Mozilla, based on their open source Gecko

rendering engine and SpiderMonkey JavaScript engine. This was the open source project

started in 1998 by Netscape, and at last, it had paid off. We were given one of the most

flexible browsers of its time, which, by following the W3C's DOM recommedations, had

given Web programmers the ability to do almost anything they wanted. Alongside that,

the Mozilla project had also adapted the java based Rhino JavaScript engine created by

Norris Boyd of the Netscape corporation, which is what had been used by ICEsoft

Technologies together with their ICE Storm architecture to produce ICEbrowser.

The largest market share was still held by Microsoft, as they released the sixth version of

their browser. In reality, this browser was more hype than anything. Its CSS support was

still far less than the Gecko engine, and by making subtle changes to its JScript,

Microsoft succeeded in causing Web developers more problems than before. Dispite this

setback, the world was finally heading towards a centrally recognised standard, the W3C

DOM.

With the release of Opera 7, which had a respectably high level of DOM support, all

major browsers had become fifth generation, and Opera stormed on to have one of the
highest levels of DOM support by version 9. Konqueror's DOM support also increase

fairly rapidly, and it quickly became a very capable DOM browser, and was soon adopted

by Apple to be part of their Safari browser, improving it for even better support of the

W3C standards.

Mozilla's popularity increased, and already the Gecko engine is used by nearly thirty

different browsers, including Netscape 6+. Firefox soon joined the ranks and did fairly

well, due in part to its Netscape and Mozilla heritage.

After leading the field for a few years, Microsoft started to get complacent, and stopped

updating their browsers. The Mac version was abandoned, and the limited updates to

Internet Explorer on Windows were merely token gestures, offering almost no increase in

the levels of DOM support. It is now far behind the others, although it supports enough

for basic DOM scripts. The W3C are now on their third DOM recommendation, which is

partially supported by Opera and Mozilla/Firefox. Most current browsers support at least

a large part of DOM 2 (Internet Explorer has finally started to support CSS 2 properly in

IE 8).

It is the hope of most Web developers that all browsers will, at some point, use the same

syntax for JavaScript. The W3C DOM may at last help that to happen. If all browser

manufacturers produced browsers that operated along the guidelines set out by the W3C,

the makers of the World Wide Web itself, Web development might actually become easy,

while still being flexible enough to create inspiring and exciting Web pages. As all

browsers would behave the same way, Web developers would not have to waste so much

time, energy and money on solving all of the many browser incompatibilities.
iCab finally gained support for DOM at version 3. The release of OmniWeb 4.5 also

brought yet another minor browse into the collective of fifth generation browsers, using

the same rendering and JavaScript core as Safari. iCab 4 has now switched to Safari's

engine. Even Escape and NetFront now have basic DOM functionality. The world of

browsers is changing, but fortunately, they are all moving in the same direction. It has

become acceptable to abandon the old proprietary technologies, and embrace a global,

flexible standard; the W3C DOM.

JavaScript name terminology

These names are subject to interpretation by the browser developers. For example,

browsers may support what they call JavaScript1.5, but not even support DHTML. This

makes the JavaScript version unreliable, do not rely on it.

ECMAscript

The core syntax for JavaScript, defining control stuctures, intrinsic objects and

variable types, operators, functions, scope, etc.

DOM level 0

Says how to refer to forms, inputs, images, links and anchors as children of the

document object.

Layers DOM

Says how to refer to positioned elements (layers) and modify their style as

children of the document object with nested references.

Proprietary DOM
Says how to refer to elements and modify their style using the all collection of the

document or parent object and the style child object of the element.

W3C DOM

Says how to refer to elements and modify their style using various

getElementBy... methods of the document or parent object and the style child

object of the element. Also says how to represent all document elements as a tree

structure. Also allows elements to be created, modified or deleted even after the

document has loaded.

Mocha

An early name for JavaScript, not recognised by most browsers.

LiveWire

An early name for JavaScript, not recognised by most browsers, used as the name

of Netscape's server side JavaScript.

LiveScript

An early name for JavaScript, recognised by most browsers.

JavaScript

A collective name for all versions of JavaScript.

JavaScript1.0

The first version of JavaScript to be released - Early ECMAscript + DOM level 0

without images.

JavaScript1.1

Early ECMAscript + DOM level 0.

JavaScript1.2
ECMAscript + DOM level 0 + layers or proprietary DOM.

JavaScript1.3

More advanced ECMAscript + DOM level 0 + layers or proprietary DOM.

JavaScript1.4

Server side JavaScript.

JavaScript1.5

Even more advanced ECMAscript + DOM level 0 + W3C DOM.

JavaScript2.0

JavaScript 1.5 with several extensions added by Mozilla - may become a future

standard.

JScript

Microsoft's JavaScript variations with extended core features.

Active scripting

Microsoft's user friendly way of saying 'JScript'.

JellyScript

WebTV's interpretation of JavaScript.

InScript

iCab 3-'s interpretation of JavaScript.

ECMAscript Mobile Profile

Parts of ECMAScript, basic JavaScript APIs, and DOM, all mixed together in a

single specification. Incompatible in far too many ways with existing pages on the

Web, current browsers, the ECMAScript specification, the DOM specifications,

the JavaScript documentation, and other well established practices. ECMAScript


Mobile Profile should be ignored. It is harmful to the Web because of its

incompatibilities.

Scope

Scope is one of the foundational aspects of the JavaScript language, and probably the one

I’ve struggled with the most when building complex programs. I can’t count the number

of times I’ve lost track of what the this keyword refers to after passing control around

from function to function, and I’ve often found myself contorting my code in all sorts of

confusing ways, trying to retain some semblance of sanity in my understanding of which

variables were accessible where.

Web Browsers

Information on the Internet is a collection of documents from all over the world linked

together by computer networks. There are several components to the Internet as outlined

in the table below:

The Internet
E-Mail WWW Usenet News FTP

Connect to Web
Send and receive Read and post Send and receive
sites
mail News files
around the world

In order to access the Internet, one needs special computer software called an

Internet browser. There are many different types of software for Internet access, however,

in this module, we will focus on two multi-component Internet software programs: 1)

Netscape (NS) and 2) Microsoft Internet Explorer (IE). Netscape and Internet Explorer

are the two most popular Internet browsers on the market today. They both have a user-

friendly, graphical interface and are capable of performing all of the functions listed in

the table above.

The most current version of Netscape (Communicator 4.X) is FREE and features the

following components:

 Messenger - an e-mail client

 Navigator - a web browser

 Collabra Discussion Groups - a usenet news client

 Composer - a web editor

 Conference - a conferencing client

The most current version of Internet Explorer (4.0) is FREE and features the following

components:

 IE WWW Browser
 IE Mail or Outlook Express - e-mail Clients

 IE News - a usenet news client

 NetMeeting - video conferencing

 FrontPage Express - web authoring tool (pared-down version of MS FrontPage)

Other browsers include such programs as Opera, NeoPlanet, and NSCA Mosaic.

Even though we will be learning about the features of Netscape and Internet Explorer,

these features are common to most popular browsers. If you are running an older

computer with less than 16 megs of RAM and have a small hard drive, you many find

that one of these browser may best suite your needs. Netscape and Internet Explorer also

have older versions for older computers.

In order to run these browsers on your personal computer you will need the

following:

 A computer running a Windows or Mac operating system

 A modem for dialing into an Internet Service Provider (ISP)

 An Internet connection to an ISP or network (usually requires establishing an

account with the provider)

 A program for dialing

o Win 95 and 98 usually come with Dial-up Networking (they have their

own Winsock software)

o Win 3.1 - you will need to get a Winsock program (ie: Trumpet Winsock)

o most current Macs come with a PPP dialing program and TCP/IP for

connecting, or you can get a copy of Free PPP


Your ISP will have all the information you need concerning this.

 The browser software

o IE comes pre-loaded with any Windows 95+ operating system. Upgraded

versions can be found at MS Internet Explorer

o Some computers come pre-loaded with NS, however, if they only have IE

you can download Netscape for free or get a copy from you ISP

Note: If you have enough memory, you can have both programs on your

computer!

Obviously, if you are using a computer at school or the public library, you need not

worry about the connection process. Most of the SCILnet schools and libraries will be

connected to the Internet with high speed lines (T1 or 56K) and will be set up by your

technology coordinator.

Starting and Closing Your Browser

To begin using your browser, double-click the icon on your desktop (or find it in your

Programs or Applications folder) to launch the program.

Netscape 3.X icon Netscape 4.X icon Internet Explorer icon


If you are using a modem, this should also launch your dialing program and connect you

to the Internet. If you are on a network, you will connect directly through the network.

What does the window look like? Well, if you are reading this...you are already there!

Note: If you are running an older version of the

browser, you can download a newer version right off

the Internet. Use the links in the Getting Connect

section above to go to your browser's home site.

To end your Internet session, make sure to exit the browser by using one of the Close

functions of your operating system. Also, if you are on a modem (a dial-up account),

make sure to close (disconnect) your dialing program, otherwise you will be connected to

the Internet and paying for time.

Working with JavaScript

JavaScript Statements

avaScript is Case Sensitive


Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely

when you write JavaScript statements, create or call variables, objects and functions.
JavaScript Statements

A JavaScript statement is a command to the browser. The purpose of the command is to

tell the browser what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people

think this is a good programming practice, and most often you will see this in JavaScript

examples on the web.

The semicolon is optional (according to the JavaScript standard), and the browser is

supposed to interpret the end of the line as the end of the statement. Because of this you

will often see examples without the semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.

Example:

<script type="text/javascript">

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

</script>
JavaScript Blocks

JavaScript statements can be grouped together in blocks.

Blocks start with a left curly bracket {, and ends with a right curly bracket }.

The purpose of a block is to make the sequence of statements execute together.

This example will write a header and two paragraphs to a web page:

Example:

<script type="text/javascript">

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

</script>

JavaScript Comments
Comments can be added to explain the JavaScript, or to make it more readable.

Single line comments start with //.

This example uses single line comments to explain the code:

Example:

<Script type="text/JavaScript">

// This will write a header:

document.write("<h1>This is a header</h1>");

// This will write two paragraphs:

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

</script>

JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.

This example uses a multi line comment to explain the code:

Example:

<script type="text/javascript">

/*

The code below will write


one header and two paragraphs

*/

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

</script>

Using Comments to Prevent Execution

In this example the comment is used to prevent the execution of a single code line:

Example:

<script type="text/javascript">

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

//document.write("<p>This is another paragraph</p>");

</script>

Do You Remember Algebra From School?

Do you remember algebra from school? x=5, y=6, z=x+y


Do you remember that a letter (like x) could be used to hold a value (like 5), and that you

could use the information above to calculate the value of z to be 11?

These letters are called variables, and variables can be used to hold values (x=5) or

expressions (z=x+y).

JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)

 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;

var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and

carname will hold the value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will

automatically be declared.

These statements:

x=5;

carname="Volvo";

have the same effect as:

var x=5;
var carname="Volvo";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;

var x;

After the execution of the statements above, the variable x will still have the value of 5.

The value of x is not reset (or cleared) when you redeclare it.

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;

z=y+5;

The operator = is used to assign values.

The operator + is used to add values.


The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

y=5;

z=2;

x=y+z;

The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result

+ Addition x=y+2 x=7

- Subtraction x=y-2 x=3

* Multiplication x=y*2 x=10

/ Division x=y/2 x=2.5

% Modulus (division remainder) x=y%2 x=1

++ Increment x=++y x=6


-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result

= x=y x=5

+= x+=y x=x+y x=15

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.

txt1="What a very";

txt2="nice day";

txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains "What a verynice

day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";

txt2="nice day";

txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";

txt2="nice day";

txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

"What a very nice day"

Adding Strings and Numbers


Look at these examples:

x=5+5;

document.write(x);

x="5"+"5";

document.write(x);

x=5+"5";

document.write(x);

x="5"+5;

document.write(x);

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference

between variables or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Example

== is equal to x==8 is false

=== is exactly equal to (value and type) x===5 is true


x==="5" is false

!= is not equal x!=8 is true

> is greater than x>8 is false

< is less than x<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take

action depending on the result:

if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this

tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true

Conditional Operator

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

some condition.

Syntax

variablename=(condition)?value1:value2

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";

Conditional Statements

Very often when you write code, you want to perform different actions for different

decisions. You can use conditional statements in your code to do this.

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>

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>

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");

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");

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");

JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script

into a function.

A function contains code that will be executed 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 can be defined both in the <head> and in the <body> section of a document.

However, to assure that the function is read/loaded by the browser before it is called, it

could be wise to put it 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 put 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.

Note: A function with no parameters must include the parentheses () after the function

name:

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 prod(a,b)

x=a*b;

return x;

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

product=prod(2,3);

The returned value from the prod() function is 6, and it will be stored in the variable

called product.

The Lifetime of JavaScript 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 Loops

Very often when you write code, you want the same block of code to run over and over

again in a row. Instead of adding several almost equal lines in a script we can use loops to

perform a task like this.

In JavaScript there are two different kind 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 will be explained in the next chapter.

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>

</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 at least 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>

</body>

</html>

Result

The number is 0

JavaScript break and continue Statements

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>

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

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

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.

Examples of events:

 A mouse click

 A web page or an image loading

 Mousing over a hot spot on the web page

 Selecting an input box in an HTML form

 Submitting an HTML form


 A keystroke

Note: Events are normally used in combination with functions, and the function will not

be executed before the event occurs!

For a complete reference of the events recognized by JavaScript, go to our complete

Event reference.

onload and onUnload

The onload and onUnload events are triggered when the user enters or leaves the page.

The onload event is often used to check the visitor's browser type and browser version,

and load the proper version of the web page based on the information.

Both the onload and onUnload events are also often used to deal with cookies that should

be set when a user enters or leaves a page. For example, you could have a popup asking

for the user's name upon his first arrival to your page. The name is then stored in a

cookie. Next time the visitor arrives at your page, you could have another popup saying

something like: "Welcome John Doe!".

onFocus, onBlur and onChange


The onFocus, onBlur and onChange events are often used in combination with validation

of form fields.

Below is an example of how to use the onChange event. The checkEmail() function will

be called whenever the user changes the content of the field:

<input type="text" size="30"

id="email" onchange="checkEmail()">

onSubmit

The onSubmit event is used to validate ALL form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will

be called when the user clicks the submit button in the form. If the field values are not

accepted, the submit should be cancelled. The function checkForm() returns either true or

false. If it returns true the form will be submitted, otherwise the submit will be cancelled:

<form method="post" action="xxx.htm"

onsubmit="return checkForm()">

onMouseOver and onMouseOut


onMouseOver and onMouseOut are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an

onMouseOver event is detected:

<a href="http://www.w3schools.com"

onmouseover="alert('An onMouseOver event');return false">

<img src="w3schools.gif" width="100" height="30">

</a>

INTRODUCTION TO HTML

WebPages are written in HTML - a simple scripting language.


HTML is short for Hyper Text Markup Language.

Hypertext is simply a piece of text that works as a link.

Markup Language is a way of writing layout information within documents.

Basically an HTML document is a plain text file that contains text and nothing else.
When a browser opens an HTML file, the browser will look for HTML codes in the
text and use them to change the layout, insert images, or create links to other pages.
Since HTML documents are just text files they can be written in even the simplest
text editor.
A more popular choice is to use a special HTML editor - maybe even one that puts
focus on the visual result rather than the codes - a so-called WYSIWYG editor ("What
You See Is What You Get").
Some of the most popular HTML editors, such as FrontPage or Dreamweaver will let
you create pages more or less as you write documents in Word or whatever text
editor you're using.
However, there are some very good reasons to create your own pages - or parts of
them - by hand...

WHY LEARN HTML?


It is possible to create WebPages without knowing anything about the HTML source
behind the page.
There are excellent editors on the market that will take care of the HTML parts. All
you need to do is layout the page.
However, if you want to make it above average in web design, it is strongly
recommended that you understand these tags.
The most important benefits are:

You can use tags the editor does not support.

 You can read the code of other people's pages, and "borrow" the cool effects.
 You can do the work yourself, when the editor simply refuses to create the
effects you want.

You can write your HTML by hand with almost any available text editor, including
notepad that comes as a standard program with Windows.
All you need to do is type in the code, then save the document, making sure to put an
.html extension or an .htm extension to the file (for instance "mypage.html").

TAGS

Basically, a computer sees an "A" as simply an "A" - whether it is bold, italic, big or
small.
To tell the browser that an "A" should be bold we need to put a markup in front of
the A.
Such a markup is called a Tag.
All HTML tags are enclosed in < and >.
Example: a piece of text as it appears on the screen.

This is an example of bold text.

HTML: the HTML for the above example:

This is an example of <b>bold</b> text.

As you can see, the start tag <b> indicates that whatever follows should be written
in bold. The corresponding end tag </b> indicates that the browser should stop
writing text in bold.

To get back to the point, <html> is the opening tag that kicks things off and tells the
browser that everything between that and the </html> closing tag is an HTML
document. The stuff between <body> and </body> is the main content of the
document that will appear in the browser window.

Closing tags

The </body> and </html> close their respective tags. ALL HTML tags should be
closed. Although older versions of HTML lazily allowed some tags not to be closed,
latest standards require all tags to be closed. This is a good habit to get into
anyway.Not all tags have closing tags like this (<html></html>) some tags, which do
not wrap around content will close themselves. The line-break tag for example,
looks like this : <br />. We will come across these examples later. All you need to
remember is that all tags must be closed and most (those with content between
them) are in the format of opening tag → content → closing tag.

Attributes
Tags can also have attributes, which are extra bits of information. Attributes appear
inside the opening tag and their value is always inside quotation marks. They look
something like <tag attribute="value">Margarine</tag>. We will come across tags
with attributes later.

Elements

Tags tend not to do much more than mark the beginning and end of an element.
Elements are the bits that make up web pages. You would say, for example, that
everything that is in-between and includes the <body> and </body> tags is the body
element. As another example, whereas '<title>' and '</title>' are tags,
'<title>Rumple Stiltskin</title>' is a title element.

LISTS

To create a bulleted list you need to add a <ul> and a </ul> tag at the beginning and
the end of the list.
Numbered lists have <ol> tags instead of <ul> tags.
To separate single list items use <li> and </li> tags.
There are special settings that you can use to customize the lists on your page.
On the following two pages you can learn in detail about bulleted and numbered
lists.

BULLETED LISTS

You have the following bullet options:

Disc

Circle

Square

Look at these examples to see the detailed syntax.


HTML-CODE EXPLANATION / EXAMPLE
Makes a bulleted list using the default bullet
<ul> type:
<li>text</li>  text
<li>text</li>  text
<li>text</li>  text
</ul>

Starts a bulleted list using discs as bullets:


 This is one line
 This is another line
<ul type="disc">
 And this is the final line

Starts a bulleted list using circles as bullets:


o This is one line
o This is another line
<ul type="circle">
o And this is the final line

Starts a bulleted list using squares as bullets:


 This is one line
 This is another line
<ul type="square">
 And this is the final line

On the next page you can learn how to create and customize numbered lists....

NUMBERED LISTS
You have the following number options:

Plain numbers
Capital Letters

Small Letters

Capital Roman Numbers

Small Roman Numbers


In addition to these options you can specify at which number the list should start. The
default start value for numbered lists is at number one (or the letter A).
Look at these examples to see the detailed syntax.

HTML-CODE EXPLANATION / EXAMPLE


Makes a numbered list using the default
<ol> number type:
<li>text</li> 1. text
<li>text</li> 2. text
<li>text</li> 3. text
</ol>

Starts a numbered list, first # being 5.


5. This is one line
6. This is another line
<ol start="5">
7. And this is the final line

Starts a numbered list, using capital letters.


A. This is one line
B. This is another line
<ol type="A">
C. And this is the final line

<ol type="a"> Starts a numbered list, using small letters.


a. This is one line
b. This is another line
c. And this is the final line

Starts a numbered list, using capital roman


numbers.
I. This is one line
<ol type="I"> II. This is another line
III. And this is the final line

Starts a numbered list, using small roman


numbers.
i. This is one line
<ol type="i"> ii. This is another line
iii. And this is the final line

Starts a numbered list, using normal numbers.


1. This is one line
2. This is another line
<ol type="1">
3. And this is the final line

An example of how type and start can be


combined.
<ol type="I" VII. This is one line
start="7"> VIII. This is another line

IX. And this is the final line


WORKING WITH HEXA DECIMAL CODES
For some reason colors in HTML are specified using hexadecimal numbers.
Hexadecimal numbers are numbers based on the value of 16 rather than the
classical numbers based on the value of 10.
When you count to 15 using hexadecimal numbers it goes like this: 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, A, B, C, D, E, F
As you see the numbers from 10 to 15 have been replaced with letters.
A typical hexadecimal color value would be A53C8D.

In this section you will learn how to understand hexadecimal color codes.
You will also learn to convert between hexadecimal and RGB color codes. (RGB
codes are used by most graphics programs to identify colors.)
Finally you will learn about an error in the color interpretation by Netscape
browsers, causing only 216 colors to look the same on all browsers.
First we will proceed to learn about the difference between hexadecimal numbers
and traditional numbers...

In classical numbers you have ten different figures, whereas in hexadecimal numbers you
have 16 different figures.
Below are numbers from 0 to 15 in both systems:

DEC 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
HEX 0 1 2 3 4 5 6 7 8 9 A B C D E F

The highest hexadecimal number you can specify using one figure is F equaling 15.
With two figures the highest value is FF equaling 255.
To prevent confusion on numbers higher than 9 hexadecimal colors are often
entered with a # in front of them.
In HTML, color codes have 6 digits, like #FF3C96.
They are explained in detail on the following pages...
RGB COLORS
Screen colors are defined by the colors Red, Green and Blue.
Therefore it is smart that HTML colors are defined in a system based on the amount
of each of the three basic colors.
This system is called an RGB color system.
(Yes, - RGB stands for Red, Green and Blue!)
Most graphics tools (Photoshop, Photo paint, Paint shop Pro etc.) can handle colors
in a RGB color system.
The problem is that while most graphics programs define the RGB code using
normal decimal numbers, HTML defines them with hexadecimal numbers.
This means, that you have to convert between decimal and hexadecimal numbers if
you want to use the same color in your graphics program and on your homepage.
We will explain the technique for this soon, but first, we will explain how RGB codes
are written in HTML...

HEXA DECIMAL RGB


A typical color definition in HTML would look like this:

<body bgColor="#FF8C67">

The color is defined to be "#FF8C67".


The # simply states that the following numbers are hexadecimal.
The first two digits are the amount of red (FF).
Digits 3 and 4 specify the amount of green (8C).
Digits 5 and 6 specify the amount of blue (67).
Below is an example showing how different colors are mixed to obtain the desired
result:

FF + 8C + 67 = FF8C67
Since there are two hexadecimal figures for each color you can specify 256 gradients
of each basic color. This gives a total of 256*256*256 = 16,777,216 different
combinations.
However, not all of these colors will look the same on all browsers and operating
systems.
Proceed to learn about the 216 colors that are "safe"...

HYPERLINKS
The tags used to produce links are the <a> and </a>.
The <a> tells where the link should start and the </a> indicates where the link ends.
Everything between these two will work as a link.
The target of the link is added to the <a> tag using
the href="http://www.whateverpage.com" setting.
The example below shows how to make the word here work as a link to yahoo.

Click <a href="http://www.yahoo.com">here</a> to go to yahoo.

You simply:

Specify the target in the <a href=" ">.

Then add the text that should work as a link.

Finally add an </a> tag to indicate where the link ends.

HTML BACKGROUNDS

When deciding whether you want to use a plain color or an image you should
consider the fact that very few of the web's 100 most visited sites use background
images.
More than 90 percent have a plain white background.
The few pages that actually do use images use very discrete and fast loading images
for the purpose.

When picking the desired color - whether it be plain or an image - you should also
consider the fact that some colors work with almost any other color - while there
are colors that only work with a limited number of contrasts.
If you use green on a red background, it will look different than if you use the same
green on a blue background. Without digging into deep theories about colors, we
will make a note on the fact that white, gray and black colors tend to be balanced
against other colors. That is, white, gray and black work with any of the colors in the
rainbow.
This is probably the reason that white, black and gray are the most widely used
background colors found on the net.

If you're designing for a company that has a certain color they use in other graphics,
it is very tempting to pick that same color for the background of the WebPages. This
might be a good idea, but there are other ways to emphasize a certain color than to
use it as background for the page.
If, for example, you see a huge white wall with a bright red dot on it, which color
makes the biggest impression on you? The 500 square feet of white or the one
square foot of red?

The conclusion is, that limited use of colors often makes the appearance of the
colors more powerful than if the entire page was one big painting.
Furthermore, when you limit your use of colors, you can use the colors more to
underscore the navigation of the page. If secondary navigation elements are held in
pale colors while primary elements are sharp - then the user will, by intuition, get
the point.
You can read more about colors on WebPages here.
Whether you want to add an image or a plain color as background you need to
specify it in the <body> tag.
Hexadecimal value. You can click here to learn about the hexadecimal system used
on HTML pages.

If you want to add a background image instead of a plain color there are some
considerations you should make before doing so:

Is the background image discrete enough to not take away the focus from what's
written on it?

Will the background image work with the text colors and link colors I set up for the
page?

Will the background image work with the other images I want to put on the page?

How long will the page take to load my background


image? Is it simply too big?

Will the background image work when it is copied to fill the entire page? In all
screen resolutions?

After answering these questions, if you still want to add the background image you
will need to specify in the <body> tag which image should be used for the
background.

<body background="drkrainbow.gif">

Note:
If the image you're using is smaller than the screen, the image will be replicated
until it fills the entire screen.
If, say you wanted a striped background for your page, you wouldn't have to make a
huge image for it. Basically you could just make an image that is two pixels high and
one pixel wide. When inserted on the page the two dots will be copied to fill the
page - thus making what looks like a full screen striped image.

When you choose to use a background image for the page it is always a good idea to
specify a background color as well.

<body background="drkrainbow.gif" bgcolor="#333333">

The reason is that until the background image is loaded, the background color will
be shown.
If there is too much difference between the background color and the background
image, it will look disturbing once the browser shifts from the background color to
the image.
Therefore it is a good idea to specify a background color that matches the colors of
the image as close as possible.

TABLES
Tables are used on websites for two major purposes:

 The obvious purpose of arranging information in a table

 The less obvious - but more widely used - purpose of creating a page layout
with the use of hidden tables.

Using tables to divide the page into different sections is an extremely powerful tool.
Almost all major sites on the web are using invisible tables to layout the pages.

The most important layout aspects that can be done with tables are:
 Dividing the page into separate sections.
An invisible table is excellent for this purpose.

Creating menus.
Typically with one color for the header and another for the links following in the
next lines.
Adding interactive form fields.
Typically a gray area containing a search option.
Creating fast loading headers for the page.
A colored table with a text on it loads like a bullet compared to even a small banner.
Easy alignment of images that have been cut into smaller pieces.
A simple way to allow text to be written in two or more columns next to each other.
The importance of using tables for these layout purposes can't be overrated.
However there are a few things to keep in mind when doing so.
Most important is, that the content of a table is not shown until the entire table is
loaded. If you have extremely long pages, you should divide it into two or more
tables - allowing the user to start reading the upper content while the rest of the
page is loading.
Now let's proceed with learning about the different techniques...
Tables are defined with the <table> tag.
To insert a table on your page you simply add these tags where you want the table
to occur:

<table>
</table>

The above table would be of no use since it has no rows and no columns.

ROWS:
To add rows to your table use the <tr> and </tr> tags.
Example:
<table>
<tr></tr>
<tr></tr>
</table>

It doesn't make sense to write the above lines in itself, cause you can't write content
outside of table cells.
If you do write things outside of cells it will appear right above the table.

COLUMNS:
You can divide rows into columns with <td> and </td> tags:
Example:

<table>
<tr> <td>This is row one, left side.</td> <td>This is row one,
right side.</td> </tr>
<tr> <td>This is row two, left side.</td> <td>This is row two,
right side.</td> </tr>
</table>

Result:

This is row one, left side. This is row one, right side.
This is row two, left side. This is row two, right side.

This page has shown the core basics of tables. In addition to these, there are
different options for customizing your tables.
The following pages will focus on the different settings for <table>, <tr> and <td>
tags.

The following properties can be added to the <table> tag:


Property Description
align=
left left align table
center center table
right right align table
background=filename image inserted behind the table
bgcolor=#rrggbb background color
border=n border thickness
bordercolor=#rrggbb border color

cellpadding=n distance between cell and content


cellspacing=n space between cells

FORMS
A form is simply an area that can contain form fields.
Form fields are objects that allow the visitor to enter information - for example text
boxes, drop-down menus or radio buttons.
When the visitor clicks a submit button, the content of the form is usually sent to a
program that runs on the server. However, there are exceptions.
Javascript is sometimes used to create magic with form fields. An example could be
when turning options in a drop-down menu into normal links.
You can use our online tool to create such a menu in less than 5 minutes - without
knowing anything about java script.
Otherwise - proceed to learn more about forms...
A typical form example would be a search engine.

SEARCH THIS SITE

This is what happens when the form is submitted:


The search words are sent to a program on the server.
The program will search a database for matches.
The program creates a webpage with the results.
The results webpage is sent back to the visitor.
Another example would be a logon page.

FREE WEB-EMAIL AT
ECHOECHO.COM

Username:

Password:

NEW USERS: SIGN UP HERE!

FORGOT YOUR PASSWORD?

This is what happens when the form is submitted:

 The ID and password are sent to a program on the server.

 The program will search a database for valid entries.


 If the entry is valid the visitor is sent to the protected page.
 If the entry is invalid the visitor is sent to a "failure" page.
Both examples send the contents of the form fields to programs running on the
server.
On the next page you will learn how to run programs that can handle your forms
(even if you technically can't do programming on your server)....

FRAMES
Frames can divide the screen into separate windows.

Each of these windows can contain an HTML document.


A file that specifies how the screen is divided into frames is called a frameset.
If you want to make a homepage that uses frames you should:
 make an HTML document with the frameset
 make the normal HTML documents that should be loaded into each of these
frames.

When a frameset page is loaded, the browser automatically loads each of the pages
associated with the frames.
A frameset is simply an HTML document that tells the browser how to divide the
screen into split windows.
The HTML for the above frameset:

<html>
<head>
<title>My Frames Page</title>
</head>

<frameset cols="120,*">
<frame src="menupage.htm" name="menu">
<frameset rows="*,50">
<frame src="welcomepage.htm" name="main">
<frame src="bottombanner.htm" name="bottom">
</frameset>
</frameset>

</html>

Note that the frameset is only seven lines!


Let's split it all up and add the lines one by one...
As stated on the previous page, a frameset is simply an HTML document that tells the
browser how to divide the screen into split windows.
If the frameset looked like this:

The code would be:

<frameset cols="120,*">
</frameset>

The screen is divided into two coloumns.


The left being 120 pixels and the right using the rest of the screen (indicated by the
*).
The frame windows would have no names, so the frameset really couldn't be used
for any purpose.
Proceed to learn how to add names and default pages that load into your frame
windows...
You can add default pages to frame windows with the src setting.
Default pages are the pages that will be loaded when the frameset is opened the first
time.
Furthermore, we can add names to each frame window using the name setting.
This will allow us to make a link in one frame window, open a page in another frame
window.
In this example we added names and default pages to the frame windows:

<frameset cols="120,*" >


<frame src="menu.htm" name="menu" >
<frame src="frontf.htm" name="main" >
</frameset>

The entire frameset will look like this:

m
e main
n
u

We still have the screen divided in two columns, the left being 120 pixels the right
using the rest of the screen. (some screens are set to 640 pixels across, some to 800
and some to 1024, that’s why the * is needed).
But now we also have told the browser that the left frame window should load an
HTML page called menu.htm and that the right window should load an HTML
document called frontf.htm.
In addition we have assigned the names menu and main to the two frame windows,
so now we're even able to link to specific windows.
We called the frame windows menu and main, but you could name them whatever
you pleased.
The frameset with a menu window to the left and a main window to the right is the
most common frameset seen on the web.
There are a few more settings we could add to the frameset.
For instance you might want the frame borders to be invisible.
To make frame borders invisible you simply need to add the parameters "cols-line"
to the frameset:

<frameset cols="120,*" frameborder="0" border="0"


framespacing="0">
<frame src="menu.htm" name="menu" >
<frame src="frontf.htm" name="main" >
</frameset>

The entire frameset would now look like this:

m
e main
n
u

We could still add a few more parameters to our frameset....


If you don’t want the frame windows to be resizable, you should add the parameter
"noresize" to the frame src lines:

<frameset cols="120,*" frameborder="0" border="0"


framespacing="0">
<frame src="menu.htm" name="menu" noresize>
<frame src="frontf.htm" name="main" noresize>
</frameset>
Now let's proceed with even more parameters for our frameset...
Lets say you don’t want a scroll bar in the menu window.
Furthermore the main window should have a scrollbar if needed (if the HTML
document doesn’t fit in the window), but if not needed - there should be no
scrollbars.
Then the code should look like this:

<frameset cols="120,*" frameborder="0" border="0"


framespacing="0">
<frame src="menu.htm" name="menu" noresize scrolling=no>
<frame src="frontf.htm" name="main" noresize scrolling=auto>
</frameset>

If you leave out the setting for scrolling, a scrollbar will appear if needed - otherwise
not.
The next page explains in detail how to link within a frameset...
If you have an HTML document with a hyperlink on the text "Analysis" for instance,
that links to a page called "analysis.htm" then it appears in the document as:

Jump to the <a href="analysis.htm">Analysis</a> of the project

Now if the link was in the menu window of our example, and we wanted it to load a
page in the main window, the HTML code would be:

Jump to the <a href="analysis.htm" target="main">Analysis</a>


of the project

We simply added the parameter target="main" to


the <a href> tag.
Now the link will be opened in the mainframe window instead of the menu frame
window where the link itself is located.
Four target names are reserved, and will be interpreted by the browser in this way:
Blank loads the page into a new browser window
Self loads the page into the current window.
Parent loads the page into the frame that is superior to the frame the hyperlink is in.
Top cancels all frames, loads in full browser window.
If you read through the pages in this section you should know just about all there is
to know about framesets in HTML.
It is possible to further enhance the control of your framesets with javascript. For
example JavaScript can prevent pages that were designed to work only within
framesets, from being loaded outside the frameset.
The last page in this section will show you examples of different framesets. You can
probably find and customize an example that is very close to what you want for your
own site....

You might also like