This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
JAVA SCRIPT 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 nonprogrammers. 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.
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. <SCRIPT LANGUAGE="JavaScript"> 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:
(Stuff about your page in general such as the title.) (The actual contents of your page.) In the area, a new pair of tags has been introduced: <SCRIPT> and 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 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. <SCRIPT LANGUAGE="JavaScript"> < !-- Beginning of JavaScript (all of your JavaScript functions) // - End of JavaScript - --> 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. <SCRIPT LANGUAGE="JavaScript"> < !-- Beginning of JavaScript function MsgBox (textstring) { alert (textstring) } // - End of JavaScript - -->
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 . 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: 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: We ended the description of the form button with: onClick="MsgBox(form.text1.value)" This means when the user clicks on this button, the program should run the MsgB ox function from the top of the page, and use the value of the form object named text1 as its variable. huh? OK, there are 2 objects in the form, a text box and a button, right? Each object has a name, and the text box is named text1. The text box's full name is form.text1. The number of characters typed in the box is called form.text1.length. The value, or string of text that was typed is called form.text1.value If this is getting too jargon-ish for you, just remember that you end your "submit" button with onClick=function(form.textboxname.value) where function and textboxname will be substituted. That's it! The value of text1 gets passed to the MsgBox function; the MsgBox function passes it to the Alert command; and the alert command displays your text for all to see!
CHAPTER-2 Show me how to do it Here is a look at the script. See if you can trace how it works. <SCRIPT LANGUAGE="JavaScript">
Explain how it works function changecolor(code) { document.bgColor=code } This page is an excellent example of one function being used by several buttons in the same document. Our function is called changecolor(code). It has only one line: document.bgColor=code.
You probably guessed that bgColor stands for background color. If I type document.bgColor="red" the background will turn red. By writing the command document.bgColor=code I am allowing myself to define the variable code as any color I want. Later, in the form. I define a button with the command: onClick="changecolor('green')" onClick="changecolor('green')" is telling the program 2 things:
1. Run the funtion named changecolor(code). 2. code='green'
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. <TITLE>Chapter 3, If-then statements <SCRIPT LANGUAGE="JavaScript">
Click the image to enter a password protected document. Try a wrong entry first.
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 } ELSE { sequence is the comparison is false } For example, let's say you've just had the reader complete a form which included their age. You want all Senior Citizens to get one message, and everyone else to get another when they submit the form. transfer the contents of the age box on the form to a age=form.age.value variable called age. The if statement begins with the question in if (age>=65) parentheses. {alert("Your form has been The alert box will be displayed if the question is submitted. Ask about our Senior true, age IS greater or equal to 65 Discounts") } The alert box command following the word ELSE ELSE {alert("Your form has been will only be displayed if the question is false, and submitted.") } age IS NOT greater or equal to 65.
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:
Show me how it's done OK, once again. Here is the script for you to look over before we go through it together. <SCRIPT LANGUAGE="JavaScript"> function encode(text) { Ref="0123456789abcdefghijklmnopqrstuvwxyz.~ABCDEFGHIJKLMNOPQRSTUVWXYZ" Result="" for (Count=0; Count
withi n Ref. It can also be used to convert numbers back to text by locating the letter at a certain position inside Ref. For example, in the English alphabet, I could easily create a code such that A=1 and B=2 because A is the first letter, and B is the second. Ref allows me to create the same code, but it includes all possible leters and number s. The letter 'a' returns a value of 10 because it is the 10th letter in from the left. (Actually it's the eleventh, but JavaScript begins counting with zero just to keep us on our toes). Later we will use the command Num=Ref.indexOf(Char) to locate the letter Char inside Ref and assign its position (how many places in) to the variable Num We'll discuss the indexOf property in more detail later. The second line of the function, Result="" is sometimes called "priming" a variable. This statement establishes that a variable called Result does exist, and that it can contain text, but does not conatin any right now. Later, I will tack letters on to the end of Result, so I need to have it in place.
Tell me about the loops
CHAPTER-4 The LOOP. 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. The LOOP - continued Here is a function designed to display an alert box with the number 1 in it, then with the number 2, then with a 3, then a 4, then a 5, and then stop.
for (count=1; count<=5; count++) { alert(count) }
How do we create the text code? A few text properties Here are a few of the text properties which we use in this function. There are properties for every type of object on your page. After you are through with this tutorial, you will be able to look up other properties from Netscape's Referenc e Page and understand how to use them. You can extract information about a piece of text by referring to one of that variable's properties. The length property tells me how many characters long a text string is. If I want to display an alert box with how many letters I typed, I would type alert(text.length).
function DisplayLength() { MyText=prompt("Type some text","") alert ( MyText.length ) } If I wanted to find the first character of a piece of text I would use the substring property. Unlike length, the substring property needs additional information in parentheses, specifically how many places in to start and stop. Remember t o alway s subtract 1 from how many characters places you want, because JavaScript begins counting the first letter as zero. var.substring ( start, stop )
function DisplayFirstChar() { MyText=prompt("Type some text","") alert ( MyText.substring(0,1) ) } The opposite of Substring is the indexOf property. Instead of returning the text at a certain position, it returns the position of a certain piece of text. For example, if I set MyText equal to "Tupperware" then the property MyText. indexO f("r") would return a value of 5. "r" is the sixth letter in, but again, JavaScript begins counting with zero.
function Display_r_position() { MyText=prompt("Type some text containing an 'r'","") alert ( MyText.indexOf("r") ) } The += operator allows me to add text to the end of an existing variable. For example, if the variable MyText="cat" then the command MyText+="erpillar" would result in MyText equalling "caterpillar." This example will tack anything you type onto the word "cat."
function AddToCat() { MyText="cat" AddOn=prompt("Type something to go after cat","") MyText += AddOn alert ( MyText) }
Put it all together function encode(text) { Ref="0123456789abcdefghijklmnopqrstuvwxyz.~ABCDEFGHIJKLMNOPQRSTUVWXYZ" Result="" for (Count=0; Count
At the start of the loop: Ref="01234567890abcdefghijklmnopqrstuvwxyz-~ABCDE...." etc. Result="" (Result is an empty placeholder) text="HAL" Command Char=text.substring (Count, Count+1); Num=Ref.indexOf (Char); EncodeChar=Ref.substring(Num+1, Num+2) Result += EncodeChar
Loop 1 Count=0 Char = "H".
Loop 2 Count=1 Char = "A".
Loop3 Count=2 Char = "L".
Num = 46. Num = 38. Num = 50. EncodeChar = EncodeChar = EncodeChar = "I" "B" "M" Result = Result = "I" Result = "IB" "IBM"
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 - 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.
Let's Learn Methods 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 <SCRIPT LANGUAGE="JavaScript">
Type a message in the box, it will become a link to close the new window.
Learn Methods //Define Date to display in local syntax now = new Date(); LocalTime = now.toLocaleString();
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()= now.getMonth()=
Day of week (0=Sunday) 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= ''+ '
Hello
'+ 'Click on the message below to close this window '+ ''+ message + ''
Creating long strings of text I can use the plus sign (+) to add text and variables together into one long piece of text. For example: The command result = "Hello " + "world" Will cause result to equal Hello world You can use the same technique to combine text with variables, like this.
mytext = prompt("what is your favorite color","") result = "Your favorite color is " + mytext result =
Next //Define contents of page contents= ''+ '
Hello
'+ 'Click on the message below to close this window '+ ''+ message + ''
Creating long strings of text The example above shows an entire HTML page defined into one variable, named contents. There are 2 reasons why I put a plus sign at the end of each line, instead of simply writing one long line of text. First, the document is much easier to read and edit this way. Second, there is a limit on how long a line of JavaScript can be. I don't know exactly what the limit is, but I know that I get errors when I create very long lines in my script. The plus sign helps me break the definition of con tents into 7 small lines instead of 1 big one. Notice the bottom 3 lines. They create a HREF link around your text. message is the contents of your sample text. If message="Hello" then the last 3 lines would read Hello
On to Chapter 6-Events 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.
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: The following table outlines all of the event handlers in NetScape version 3.0 (SOURCE: NETSCAPE'S JAVASCRIPT REFERENCE PAGE)
Event abort
blur click
change
Applies to images
Event handler onAbort
Occurs when User aborts the loading of an image (for example by clicking a link or clicking the Stop button) User removes input focus from onBlur window, frame, or form element User clicks form element or link onClick
windows, frames, and all form elements buttons, radio buttons, checkboxes, submit buttons, reset buttons, links text fields, textareas, select User changes value of element lists
onChange
error
images, windows
focus
windows, frames, and all form elements document body
load
mouseout areas, links
mouseover links reset
forms
select
text fields, textareas
submit unload
submit button document body
The loading of a document or onError image causes an error User gives input focus to window, onFocus frame, or form element User loads the page in the onLoad Navigator User moves mouse pointer out of onMouseout an area (client-side image map) or link User moves mouse pointer over a onMouselink Over User resets a form (clicks a Reset onReset button) User selects form element's input onSelect field User submits a form onSubmit 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.
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.
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 }