Professional Documents
Culture Documents
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."
I teach computer classes for a living to corporate clients of all levels. After 2 years of teaching, I
have learned a lot about communication between people of various levels of computer
experience. This tutorial assumes that you have no prior programming experience, but that you
have created your own HTML pages.
If you find this tutorial helpful, please let me know (it's my only reward). Also, links are graciously
accepted.
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.
<BODY>
<FORM>
<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(form.text1.value)">
</FORM>
</BODY>
</HTML>
First of all, remember that your HTML page is divided into 2 segments, the HEAD and the BODY.
You set up your page this way:
<HTML>
<HEAD>
(Stuff about your page in general such as the title.)
</HEAD>
<BODY>
(The actual contents of your page.)
</BODY>
</HTML>
In the <HEAD> area, a new pair of tags has been introduced: <SCRIPT> and </SCRIPT>
All browsers currently assume you are programming in JavaScript, but other programming
languages might come along in the future. As a result, it is standard form to open your scripting
area with:
<SCRIPT LANGUAGE="JavaScript">
The <!-- and --> tags are used to hide comments in HTML from the browser. Old browsers will not
understand the <SCRIPT> tags, so you need to include the comment tags to keep your
JavaScript from showing up on the Browser.
This is the standard open and close to the JavaScript section of your page.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
< !-- Beginning of JavaScript -
(all of your JavaScript functions)
// - End of JavaScript - -->
</SCRIPT>
</HEAD>
You can name your functions anything you want. I chose to name mine MsgBox, but I could have
named it Kalamazu or something else.
A function is typed like this:
function MyFunction (variable) {
(stuff you want to do with the variable)
}
This animation shows how a number can be passed to the variable "data" and then used in a
function written for that variable.
The variable can be a number, a piece of text, or a date.
The curly brackets { } define the beginning and end of the function.
The alert command will create an message box displaying a piece of text or a number.
Alert("Hello World") will display Hello World in the box.
Alert(SomeText) will assume that SomeText is a variable, and will display whatever value it
contains. Notice that "Hello World" was in quotes and SomeText was not. If I put these two lines
together:
SomeText="My Three Sons"
Alert(SomeText)
then My Three Sons will be displayed in the message box.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
< !-- Beginning of JavaScript -
function MsgBox (textstring) {
alert (textstring) }
// - End of JavaScript - -->
</SCRIPT>
</HEAD>
The Form is a JavaScript user's best friend. Forms can be used to input text, to display results,
and to trigger JavaScript functions. The form in our example used 2 objects, a text box, and a
button.
All forms start with the tag <FORM> and end with </FORM>.
The text box should include a NAME and a TYPE
The NAME will be used when we need to tell the function which box has the text we want.
TYPE is how the browser knows to create a text box, button, or check box.
For example:
<INPUT NAME="text1" TYPE=Text>
The button is how we tell JavaScript to run a particular function. The button should include a
NAME, TYPE, VALUE, and ONCLICK command.
The NAME could be used to refer to the button in JavaScript, but is usually not important.
The VALUE is the label which will appear inside the button.
The ONCLICK is followed by the name of a function, and the name of the text box containing the
data.
For example:
<INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(form.text1.value)">
<BODY>
<FORM>
<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(form.text1.value)">
</FORM>
</BODY>
</HTML>
CHAPTER-3
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>
function password() {
Ret = prompt('Type the word castle',"");
if(Ret=="castle") {
location = 'ch03_1.html';
The prompt
The first line of the function, password() is:
Ret = prompt('Type the word castle',"");
This command tells the computer to open a prompt box, and assign whatever the
user types to the variable, Ret. Therefore if the user types "chickensoup", the
computer will execute the command
Ret="chickensoup"
I can then compare the variable Ret with other text to determine if the user typed
in the correct password.
The parentheses contain the message inside the prompt box, then the default
text. Look at this sample command, then click the show me button
prompt("Please type your name","Newt")
If you do not want a default, simply place 2 quotes after the comma like I did in
the original example.
if(Ret=="castle") {
location = 'ch03_1.html';
} else {
alert("Please try again")
}
The if-then statement
The second line of the function is an if-then statement. It tells the computer that if
the variable Ret equals "castle" then change the URL location to ch03_1.html.
Otherwise, show the alert box which says "Please try again."
Here is the format of an if-then statement:
IF (a comparison)
{ sequence if the comparison is true }
<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>
The LOOP.
CHAPTER-4
The loop is a fantastic tool for any function that involves doing the same thing more than once. If I
wanted to write my name 10 times, I would write a loop like this:
START LOOP (REPEAT 10 TIMES)
Write my Name
END OF LOOP
Of course that's not how I would type it. To create a loop I need to use the FOR statement. It is
written like this:
for ( count=1; count <=10; count++ ) {
(stuff I want to do 10 times)
}
This statement would be read outloud:
"For count equals one, while count is less than or equal to ten, incrementing by one"
The FOR statement above will begin by creating a variable called count (you can choose any
variable name). Initially, count will equal 1. The computer will perform whatever commands are
between the curly bracket s, then upon reaching the end of the loop, count is incremented by 1,
and a question is asked: IS COUNT LESS THAN OR EQUAL TO 10? If the answer is YES, then
the loop repeats. If the answer is no, then the progr am exits the loop, and goes on with the
program.
CHAPTER-5
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
Before you can do anything which involves the current date/time, you have to set a variable equal
to the current date. now = new Date() is command to get the current date and time from the
user's computer, and assign it to the variable, now in one long string.
toLocaleString() is a method which converts the raw date/time string of text into the local
convention. Depending on what country JavaScript thinks the user is in, the toLocaleString()
may present the month first, or the day first.
now =
now.toLocaleString() =
Here are some other Date methods:
If now =
now.getDay()= Day of week (0=Sunday)
now.getMonth()= Month (0 to 11)
now.getDate()= Day of month
now.getYear()= Year
Note: IE returns a 4 digit year, Netscape returns the number of years since 1900. Use this syntax:
year=getYear();
if (year<1900) {year+=1900};
now.getHours()= Hours
now.getMinutes()= Minutes
now.getSeconds()= Seconds
now.getTime()=
..........Milliseconds since January 1, 1990 at Midnight.
now.gettimezoneOffset()= minutes off from GMT
Next
//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>'
result =
Next
//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>'
result =
As you can see, the <A HREF> tag can be used to trigger javascript events instead of creating a
link to another page. We will discuss this in more detail later.
More about windows
//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();
For example, let's say I created a page called mytest.htm. It might be as simple as this:
<HTML><HEAD>
<TITLE>Test Page </TITLE>
</HEAD>
<BODY>
This is only a test
</BODY> </HTML>
I could open it into a new window like this.
NewWindow = window.open("mytest.htm")
Next Page
//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();
Writing to a document
You can create an HTML document 'on the fly' with JavaScript using the document.write()
method. Normally, you must open a new document first. Then you may write to that document,
and finally you must close the document so that the Browser can stop tryi ng to load it. Here is an
example:
document.open()
document.write("Hello There")
document.close()
When I create a new window, I am also opening a new document. So I can write to a new window
with this series of commands.
NewWindow = window.open("","","width=200,height=200")
NewWindow.document.write("Hello There")
NewWindow.document.close()
The document.write() method can contain either text or a variable inside the perentheses. The
following example creates a variable, then writes the variable to a new document.
SampleText = "Hello there, " +
"It's nice to see you again."
NewWindow = window.open("","","width=200,height=200")
NewWindow.document.write(SampleText)
NewWindow.document.close()
I can even include HTML tags in the document.write() statement. Like this:
NewWindow = window.open("","","width=200,height=200")
NewWindow.document.write("<CENTER><H1>Hello there</H1></CENTER>")
NewWindow.document.close()
More about document.write()
Writing to a document
With just a little creativity, you can have JavaScript create fully formatted web pages on the fly.
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 a onMouse-
link Over
reset forms User resets a form (clicks a Reset onReset
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
More about Events
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
loses focus. 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 event.
More Events
onChange Events
Certain types of form objects, such as checkboxes and menus can't have a text cursor, so they
can't trigger an onBlur event when you make changes. You can use the onChange event to
trigger your functions when the user has make his/her selec tion on these items.
<SCRIPT>
function getSelect(s) {
return s.options[s.selectedIndex].value
}
</SCRIPT>
<FORM>
<SELECT NAME="list" SIZE=1 OnChange="location=getSelect(this)">
<OPTION value="#"> Choose a search engine
<OPTION value="http://www.yahoo.com"> Yahoo
<OPTION value="http://www.lycos.com"> Lycos
<OPTION value="http://www.excite.com"> Excite
</SELECT>
<FORM>
Since Netscape forgot to provide a function for getting the value of a select box, I wrote one
which I place in the <SCRIPT> tags of any page that has a selection list. Simply copy the
getSelect(s) function into your <SCRIPT> area, and getSelect(form.mylist) will return the Value
of the current mylist selection.
In this example we used the word this as a shortcut. We could have said getSelect(form.list),
however since the command was inside the <SELECT> tag, the word this automatically referred
to the current <SELECT> object. In this example, if Lycos was selected, then the event
onChange="location=getSelect(this)" would be interpreted as
location="http://www.lycos.com".
Check Boxes
Since a checkbox is selected/deselected with a mouse click, the onClick event will trigger your
function whenever the checkbox is changed. Each checkbox has a property called checked
which is equal to true or false depending on whether the box is currently checked. This example
runs a function when the box is clicked, and displays a message if the box is checked.
function rushbox(checked) {
if (checked==true) {alert(" LIFT OFF! ")}
}
<FORM>
<INPUT TYPE=checkbox NAME="rush" OnClick="rushbox(form.rush.checked)"
Rush this order <FORM>
Rush this order
Page Load events
onLoad Events
Upon loading this page, a window appeared with a welcome message in it. The window stayed
for 5 seconds, then closed. If you want to see it again, click RELOAD
The onLoad event is placed in the <BODY> tag, and it is used to trigger events automatically
upon loading the page. You can use the onLoad to display a welcome message, place the focus
in a particular textbox, execute a special effect, o r prompt for a password. The <BODY> tag of
this page looks like this:
<BODY bgcolor="white" onLoad="MsgBox()">
MsgBox() is a function in the <SCRIPT> area which opens a window, then closes it after 5
seconds. We will discuss the setTimeout() method used to close the window automatically in
more detail later.
How about onUnload events?
onUnload Events
As you may have guessed, the onUnload() event handler will trigger an event when the user
exits the current page.
I had this page open into a new window so that you can experiment with the onUnload event
handler without losing your place in the tutorial.
Here is the <BODY> tag at the top of this document.
<BODY BGCOLOR="white" onUnload="alert('Please come back soon')"
Use any method you like to leave this page. Click the back button, type a URL into the location
box, reload, close the window, or follow a link like this one.
Click to see a cute animation.
No matter how you leave the page the onUnload() event will trigger.
Yes you can use onUnload to make a page difficult to leave, but this would quickly result in a very
lonely web site.
Next
**BONUS CHAPTER**
This 15 page chapter is available only as part of the downloaded zip file.
The cost for this entire tutorial is a very reasonable $7.75 US.
It also includes a printable text file of the entire tutorial,
and a cheat sheet (quick reference) of all the codes used in the tutorial.
Click Here to download this file.
Chapter 7, special effects!
The glowing button
A reasonably secure Replacing Images
password box. Enter the Using option menus
word 'scarlet.' The The Image Map
password does not exist
anywhere in the source
secure password
code. status bar messages
BY
G.Yogeshwar Dayalb{A Virus ProgrammAr And Hacker}