Вы находитесь на странице: 1из 14

Welcome To JavaScript for the Total Non-Programmer

This tutorial will take you step by step through the fundamentals of Javascript. You will
learn how to write functions, use data from text boxes, create IF-THEN conditionals,
program loops, and generally make your web page "smarter."

What is JavaScript?

Javascript is an easy-to-use programming language that can be embedded in the header


of your web pages. It can enhance the dynamics and interactive features of your page by
allowing you to perform calculations, check forms, write interactive games, add special
effects, customize graphics selections, create security passwords and more.

What's the difference between JavaScript and Java?

Actually, the 2 languages have almost nothing in common except for the name. Although
Java is technically an interpreted programming language, it is coded in a similar fashion
to C++, with separate header and class files, compiled together prior to execution. It is
powerful enough to write major applications and insert them in a web page as a special
object called an "applet." Java has been generating a lot of excitment because of its
unique ability to run the same program on IBM, Mac, and Unix computers. Java is not
considered an easy-to-use language for non-programmers.

Javascript is much simpler to use than Java. With Javascript, if I want check a form for
errors, I just type an if-then statement at the top of my page. No compiling, no applets,
just a simple sequence.

What is Object Oriented Programming?

Everyone that wants to program JavaScript should at least try reading the following
section. If you have trouble understanding it, don't worry. The best way to learn
JavaScript is from the examples presented in this tutorial. After you have been through
the lessons, come back to this page and read it again.

OOP is a programming technique (note: not a language structure - you don't even need
an object-oriented language to program in an object-oriented fashion) designed to
simplify complicated programming concepts. In essence, object-oriented programming
revolves around the idea of user- and system-defined chunks of data, and controlled
means of accessing and modifying those chunks.

Object-oriented programming consists of Objects, Methods and Properties. An object is


basically a black box which stores some information. It may have a way for you to read
that information and a way for you to write to, or change, that information. It may also
have other less obvious ways of interacting with the information.

Some of the information in the object may actually be directly accessible; other
information may require you to use a method to access it - perhaps because the way the
information is stored internally is of no use to you, or because only certain things can be
written into that information space and the object needs to check that you're not going
outside those limits.

The directly accessible bits of information in the object are its properties. The difference
between data accessed via properties and data accessed via methods is that with
properties, you see exactly what you're doing to the object; with methods, unless you
created the object yourself, you just see the effects of what you're doing.

Other Javascript pages you read will probably refer frequently to objects, events,
methods, and properties. This tutorial will teach by example, without focusing too heavily
on OOP vocabulary. However, you will need a basic understanding of these terms to use
other JavaScript references.

Objects and Properties

Your web page document is an object. Any table, form, button, image, or link on your
page is also an object. Each object has certain properties (information about the object).
For example, the background color of your document is written document.bgcolor. You
would change the color of your page to red by writing the line: document.bgcolor="red"

The contents (or value) of a textbox named "password" in a form named "entryform" is
document.entryform.password.value.

Methods

Most objects have a certain collection of things that they can do. Different objects can do
different things, just as a door can open and close, while a light can turn on and off. A
new document is opened with the method document.open() You can write "Hello World"
into a document by typing document.write("Hello World") . open() and write() are both
methods of the object: document.

Events
Events are how we trigger our functions to run. The easiest example is a button, whose
definition includes the words onClick="run_my_function()". The onClick event, as its
name implies, will run the function when the user clicks on the button. Other events
include OnMouseOver, OnMouseOut, OnFocus, OnBlur, OnLoad, and OnUnload.

Webteacher Software now offers

Chapter 1, The Message Box

This is a very simple script. It opens up an alert message box which displays whatever is
typed in the form box below.

Type something in the box. Then click "Show Me"

HOW IT'S DONE

Here's the entire page, minus my comments. Take a few minutes to learn as much as
you can from this, then I'll break it down into smaller pieces.

<HTML>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -

function MsgBox (textstring) {


alert (textstring) }

// - End of JavaScript - -->


</SCRIPT>

</HEAD>

<BODY>
<FORM>
<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me"
onClick="MsgBox(form.text1.value)">
</FORM>

</BODY>
</HTML>
Changing background color with button

Webteacher Software now offers

Chapter 1, The Message Box

This is a very simple script. It opens up an alert message box which displays whatever is
typed in the form box below.

Type something in the box. Then click "Show Me"

HOW IT'S DONE

Here's the entire page, minus my comments. Take a few minutes to learn as much as
you can from this, then I'll break it down into smaller pieces.

<HTML>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -

function MsgBox (textstring) {


alert (textstring) }

// - End of JavaScript - -->


</SCRIPT>

</HEAD>
<BODY>

<FORM>
<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me"
onClick="MsgBox(form.text1.value)">
</FORM>

</BODY>
</HTML>
Click on photo for password

Webteacher Software now offers

The if-then statement.

OK, once again, here is the entire code. Give it a look, then we'll break it down. This is a
good example of an If-Then statement. Password scripts can also be combined with an
encryption function so that hackers can't break in simply by viewing your source code.
The purpose of this chapter, however, is to give you some practice with if-then
statements.

<HTML>
<HEAD>
<TITLE>Chapter 3, If-then statements</TITLE>

<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -

function password() {

Ret = prompt('Type the word castle',"");


if(Ret=="castle") {
location = 'ch03_1.htm';
} else {
alert("Please try again")
}
}

// - End of JavaScript - -->


</SCRIPT>
</HEAD>
<BODY>

<A HREF="javascript:password()">
<IMG SRC="pict1.gif" NAME="pic1" ALT="about us!" BORDER="0" align="left"></A>

<H3>Click the image to enter a password protected document. Try a wrong entry
first.</H3>

</BODY>
</HTML>

Webteacher Software now offers

The following is an example of the simple 'alphabet code.' Each letter


in your word is offset by 1 letter, so that 'A' becomes 'B' and 'B'
becomes 'C' etc. Try entering HAL, the computer from 2001.

Type your word


Result:

Webteacher Software now offers

The following is an example of the simple 'alphabet code.' Each letter


in your word is offset by 1 letter, so that 'A' becomes 'B' and 'B'
becomes 'C' etc. Try entering HAL, the computer from 2001.
Type your word
Result:

OK, once again. Here is the script for


you to look over before we go through it together.

<HTML>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -

function encode(text) { Ref="0123456789abcdefghijklmnopqrstuvwxyz.-


~ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Result=""
for (Count=0; Count<text.length; Count++) {

Char=text.substring (Count, Count+1);


Num=Ref.indexOf (Char);
EncodeChar=Ref.substring(Num+1, Num+2)
Result += EncodeChar
}
document.form1.result.value=Result
}

// - End of JavaScript - -->


</SCRIPT>

</HEAD>
<BODY bgcolor="beige">

<FORM name="form1">
<table border=0><tr><td>
Type your word<td><INPUT NAME="input" TYPE=Text><br><td>
<INPUT TYPE=Button VALUE="submit"
onClick="encode(this.form.input.value)"><tr><td>
Result:<td><INPUT NAME="result" TYPE=Text>

</table>
</FORM>
</BODY>
</HTML>

Methods

When you need to DO something, like open a window, write text to the screen, get the
sin of a number, isolate the 1st letter in a word, assign today's date to a variable, send
the user back to the previous page, or display an alert box you are using a method.

When you change the details about something which already exists, you are changing its
properties.

For example:
document.bgcolor="red" is a property because I'm changing the existing details about
the document. alert("Hello There") is a method because it creates something new, an
alert box.

Here are a few types of commands that methods are useful for.

• Date Methods - set variables to the clock time in a variety of ways.


• Window Methods - used to open and close new windows
• Document Methods - Generate new documents on the fly.
• Form Methods - select form items, send the cursor to text boxes and submit
forms.
• History Methods - Press the reader's 'Back' button and other tricks.
• Text Methods - Define the look of your text variables before your display them.
• Math Methods - sin, cos, round, random, absolute value, etc.
• MessageBox Methods - Alert, Prompt, and Confirm are all methods

METHOD EXAMPLE

Type a message in the box,


it will become a link to close the new window.

You guessed it, here is the code


Look it over, then we'll break it on down
<HTML>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -

function MyWindow(message) {

//Define Date to display in local syntax


now = new Date();
LocalTime = now.toLocaleString();
//Define contents of page
contents=
'<body bgcolor="beige">'+
'<h2>Hello</h2>'+
'Click on the message below to close this window<br>'+
'<A HREF="javascript:window.close()" >'+
message +
'</A>'
//Create new Window
options = "toolbar=0,status=0,menubar=0,scrollbars=0," +
"resizable=0,width=300,height=200";
newwindow=window.open("","mywindow", options);
newwindow.document.writeln(LocalTime);
newwindow.document.write(contents);
newwindow.document.close();
}

// - End of JavaScript - -->


</SCRIPT>

</HEAD>
<BODY bgcolor="white" onLoad="this.form1.text1.focus()">

<TABLE BORDER=1 bgcolor="beige"><tr><td><B>Type a message in the box, <br>it


will become a link to close the new window.</B>
<FORM NAME="form1">
<INPUT NAME="text1" TYPE=Text SIZE="50" MAXLENGTH="50"><br>
<INPUT TYPE=Button VALUE="Create my window"
onClick="MyWindow(form.text1.value)">
</FORM></TABLE>

</BODY>
</HTML>
EVENTS

Every object on your page has certain 'Events' which can trigger your JavaScript
functions. For example, we use the 'onClick' event of the form button to indicate that a
function will run when the user clicks that object. We define the events in the same
HTML tag which we use to place an object on the screen. So a button which runs
'myFunction()' when clicked will be written this way.

<input type=button value="click me" onClick="myFunction()">

I could also use onMouseOver to make an event happen when the user's mouse is over
certain objects. For instance a message could appear in an alert box.

Images can't have events, but links can. So I added an onMouseOver event to the
above image by creating a link to nothing around it. Here is the code for the above
image:

<A HREF="#" OnMouseOver="alert('hi')">


<IMG SRC="http://images.webteacher.com/javascript/images/pointme.gif" BORDER=0 >
</A>

The following table outlines all of the event handlers in NetScape version 3.0
(SOURCE: NETSCAPE'S JAVASCRIPT REFERENCE PAGE)

Event
Event Applies to Occurs when handler
abort images User aborts the loading of an onAbort
image (for example by clicking a
link or clicking the Stop button)
blur windows, frames, and all User removes input focus from onBlur
form elements window, frame, or form element
click buttons, radio buttons, User clicks form element or link onClick
checkboxes, submit buttons,
reset buttons, links
change text fields, textareas, select User changes value of element onChange
lists
error images, windows The loading of a document or onError
image causes an error
focus windows, frames, and all User gives input focus to window, onFocus
form elements frame, or form element
load document body User loads the page in the onLoad
Navigator
mouseout areas, links User moves mouse pointer out of onMouseout
an area (client-side image map)
or link
mouseover links User moves mouse pointer over onMouse-
a link Over
reset forms User resets a form (clicks a onReset
Reset button)
select text fields, textareas User selects form element's input onSelect
field
submit submit button User submits a form onSubmit
unload document body User exits the page onUnload

EVENTS IN A FORM

There are 3 events which I find particularly useful when working in a form.

• onFocus
• onBlur
• onChange

FOCUS means the object where the cursor is currently blinking. OnFocus events occur
whenever the cursor enters that textbox or textarea. It doesn't matter whether the user
placed the cursor there with the mouse or with the TAB key. As soon as the cursor enters
a box, an OnFocus event attached to that box wil l occur.

<FORM>
<INPUT TYPE=TEXT SIZE=20 onFocus="window.status='Hi there';return true">
</FORM>

BLUR is the opposite of focus. Therefore an onBlur event will occur whenever a text
object losesfocus. Here is the same example again, but the alert will occur when you try
to leave the box.

<FORM>
<INPUT TYPE=TEXT SIZE=20 onBlur="window.status='Bye now';return true">
</FORM>

Try moving the focus from the second example to the first, and the message will appear
twice, once because you left the box with an onBlur event, and once because you
entered a box with an onFocus