+ All Categories
Home > Documents > Javascript Tutoriallll

Javascript Tutoriallll

Date post: 03-Dec-2014
Category:
Upload: lokesh-verma
View: 27 times
Download: 0 times
Share this document with a friend
98
Well, its time to try out your first javascript. This one is nice because we don't have to deal with adding the script tag. This little script will write something of your choice to the browser's status bar when you move your mouse over a link. Let's look at the example: <A HREF="jmouse.htm" onMouseover="window.status='Hi there!'; return true">Place your mouse here!</A> I'll explain all this in a second. Go ahead and see what it does. Place your mouse pointer over the link, but don't click it. Now look down at the status bar at the bottom of your browser. It will say "Hi there!" Place your mouse here! Okay, here's what is happening with the onMouseover command: 1. onMouseover=" " This is the form of the onMouseover command. The browser expects another command or function inside the quote marks. 2. window.status='Hi there!' This command instructs the browser to write to the status bar. You place what you want the browser to write inside the single quote marks. 3. return true Returns the statement as true so the browser will display the text. The reason for the single quote marks is because in this case, the window.status command is used inside the onMouseover command, which was already using double quotes. If we had used another set of double quotes, the browser would have gotton confused about what it should do because it would think the onMouseover command had ended when we began the window.status command: onMouseover=""window..... Well, one thing that could be bugging you is the fact that the "Hi There!" is now in your status bar and won't leave. There are two ways to fix this problem. One way is to use the onMouseout command, and another is to call a function that will erase the text after a specified amount of time. The second way requires using functions and the script tags, so for now I will show you the easiest way to do it: the onMouseout command. Here it is: <A HREF="jmouse.htm" onMouseover="window.status='Hi there!'; return true" onMouseout="window.status=' '; return true">Place your mouse here!</A> Keep all of the code above on one line, the line breaks above for the ease of reading the code. This will make the text disappear from the status bar when you move your mouse off of the link. Give it a try:
Transcript
Page 1: Javascript Tutoriallll

Well, its time to try out your first javascript. This one is nice because we don't have to deal with adding the script tag. This little script will write something of your choice to the browser's status bar when you move your mouse over a link. Let's look at the example:

<A HREF="jmouse.htm" onMouseover="window.status='Hi there!'; return true">Place your mouse here!</A>

I'll explain all this in a second. Go ahead and see what it does. Place your mouse pointer over the link, but don't click it. Now look down at the status bar at the bottom of your browser. It will say "Hi there!"

Place your mouse here!

Okay, here's what is happening with the onMouseover command:

1. onMouseover=" "This is the form of the onMouseover command. The browser expects another command or function inside the quote marks.

2. window.status='Hi there!'This command instructs the browser to write to the status bar. You place what you want the browser to write inside the single quote marks.

3. return trueReturns the statement as true so the browser will display the text. 

The reason for the single quote marks is because in this case, the window.status command is used inside the onMouseover command, which was already using double quotes. If we had used another set of double quotes, the browser would have gotton confused about what it should do because it would think the onMouseover command had ended when we began the window.status command:   onMouseover=""window.....

Well, one thing that could be bugging you is the fact that the "Hi There!" is now in your status bar and won't leave. There are two ways to fix this problem. One way is to use the onMouseout command, and another is to call a function that will erase the text after a specified amount of time. The second way requires using functions and the script tags, so for now I will show you the easiest way to do it: the onMouseout command. Here it is:

<A HREF="jmouse.htm" onMouseover="window.status='Hi there!'; return true" onMouseout="window.status=' '; return true">Place your mouse here!</A>

Keep all of the code above on one line, the line breaks above for the ease of reading the code. This will make the text disappear from the status bar when you move your mouse off of the link. Give it a try:

Place your mouse here!

We did the same thing as before, except inside the onMouseout command we used a space inside the window.status command rather than text. This script is pretty fun, and can be helpful for your visitors if you use your text to describe where a link will take them.

Well, now that you have this, let's see about using buttons and the "onClick" command to make some things happen. Let's go on to Using Buttons for JavaScripts. 

Page 2: Javascript Tutoriallll

To write scripts using buttons, we will first need to know how to place a button on the page. To do this, you will need to use the <FORM> tags around the button tag. Here is an example of the HTML that will place a button on the page:

<FORM> <INPUT type="button" value="Click Me" name="button1"> </FORM>

This will place a button on your page, but if you click on it nothing will happen....

Here is what all this means:

1. <FORM>This creates a form so we can use a button.

2. <INPUT>This tag allows us to create an input area of some kind.

3. type="button"This command declares our input area to be a button.

4. value="Click Me"This will be the text people will see on the button. Write whatever you want your visitors to see.

5. name="button1"You can give the button a name for future reference and possibly for use in a script. 

Now, I know you don't just want to make buttons that don't do anything, so let's look at a javascript command that will make the browser do something when a viewer clicks it:

onClick="javascript commands"

Just place this command inside the INPUT tag you created the button with, like this:

<INPUT type="button" value="Click Me" name="button1" onClick=" ">

Now, if you read the last section, you saw how to add text to the status bar using the onMouseover command. Well, you can also use a button to do this!

<FORM> <INPUT type="button" value="See Some Text" name="button2" onClick="window.status='You clicked the button!'; return true"> </FORM>

Now click the button below and see the text in the status bar at the bottom:

Page 3: Javascript Tutoriallll

You can also allow your viewers to change the background color of your page. Just use the following command, rather than the window.status command:

document.bgColor='color'

Just insert this as your instructions for the onClick command, like this:

<FORM> <INPUT type="button" value="Change to Yellow!" name="button3" onClick="document.bgColor='yellow'"> </FORM>

Now you get the button below. Click on it to see this page with a yellow background!

You can add as many of these buttons as you like, just be sure they have the option to change back to the original color. The next script will give you three choices: yellow, red, and original color.

<FORM> <INPUT type="button" value="Change to Yellow!" name="button3" onClick="document.bgColor='yellow'"> <br> <INPUT type="button" value="Change to Red!" name="button4" onClick="document.bgColor='red'"> <br> <INPUT type="button" value="Change back!" name="button5" onClick="document.bgColor='white'"> </FORM>

Now you will have these buttons. Give them a try!

  

The last script we will do in this section will allow you to use your button as a link. It's pretty fun to use every now and then. Just use the following command in your onClick command:

window.location='url'

Here is a script that will send you to a page I made just for this example:

<FORM> <INPUT type="button" value="Go to my other Page!" name="button6" onClick="window.location='http://www.pageresource.com/jscript/newpage.htm'"> </FORM>

Here is the button. Give it a try, and see the other page.

Page 4: Javascript Tutoriallll

That does it for now, let's go on to History Buttons. 

Well, you want to make a back button- but you want the button to take the viewer back to the page they just came from, which may not have been one of your pages. This kind of back button would act like the back button on a web browser. Well, if you really want to have one, you can do it with a nifty little javascript. Here it is:

<FORM> <INPUT type="button" value="Click here to go back" onClick="history.back()"> </FORM>

This will place a button on your page that will send the user back to the last page in their history list before yours. To try it out, click the link below and see the button on the new page.

Example Page

And when you clicked the button, you ended up back here. You can try going to the example page from elsewhere......you'll just be sent back there when you click the button....

So, what does all of that code mean? Okay, here's the scoop:

1. <FORM>This opens a form so we can use the button on the page.

2. <INPUT type="button" value="Click here to go back".....This creates the button we use for the script.

3. ....onClick="history.back()">This is what makes everything happen. The onClick=" " tells the browser to do the command in the quotes when the button is clicked. The history.back() is the function that does just what it says: It takes the viewer on step back in their history list. 

Is there more? ..I thought you'd never ask......

Page 5: Javascript Tutoriallll

Okay, you can swap out the history.back() function above with one of the following to do some different things:

1. history.forward()This will take the viewer one step forward in their history list.

2. history.go(-1) or history.go(1)This allows you to determine how far forward or back to take the viewer. Use a minus sign and a number to go back, or just a number to go forward. 

Try really confusing somebody by using -7 or 12 or something. I sure would wonder what happened if I ended up seven pages back from where I was!

That does it for now, let's go on to JS Alerts 

Well, you want to add one of those JavaScript alert boxes that come out of nowhere, don't you? Okay, let's begin with the alert box that just tells the viewer something you want them to know. Here's the alert command:

alert('your choice of text')

Now, to use it, we'll need to place it inside another command. Let's use one we are familiar with, the onMouseover command. The following script will alert the user that you did not want them trying to click this particular link when they move their mouse over it.

<A HREF="noplace" onMouseover="alert('Hey! I said not to try clicking this link!')"> Don't click this link!</A>

Give it a try. Move your mouse over the link below:

Don't click this link!

Yes! Now you can drive your friends insane with a bunch of fake links! Here's what all the commands are doing:

1. onMouseover=" "This tells the browser to execute the command or function inside the double quote marks when the user moves their mouse over the link.

2. alert('Hey! I said not to try clicking this link!')Instructs the browser to display the text inside the single quotes in an alert window. 

That was nice, but could you make something a little more annoying? Of course! It's called the "alert as soon as you open the page!" alert. Just think, you could tell people stuff before they ever see anything on the page! The trick: placing the alert command inside the <HEAD> </HEAD> tags! You will now get to use the old SCRIPT tags I mentioned a couple of sections ago to set off the JavaScript from the other stuff. Here is the code:

Page 6: Javascript Tutoriallll

<HEAD> <TITLE>Cool JavaScripts</TITLE> 

<SCRIPT language="JavaScript"> <!-- hide from old browsers 

alert('Welcome to my Web Site!'); 

//--> </SCRIPT> 

</HEAD>

This will display the alert before the page starts loading. When you hit "OK" the page will go on and load normally.

Here's the breakdown:

1. <SCRIPT language="JavaScript">This tag lets the browser know you are using JavaScript commands here.

2. <!-- hide script from old browsersThis makes sure older browsers don't display your script as text on the page.

3. alert('Welcome to my Web Site!');This is your alert. Put your mesage inside the single quotes. Notice the semicolon at the end, this is what separates JavaScript commands.

4. //-->Stops hiding the script from old browsers.

5. </SCRIPT>Ends the JavaScript commands. 

Do you want to try it out? Click on the link to see the alert before the new page.

Example 1

So, do you want to get carried away? Place several of these alerts inside the SCRIPT tag, following each with a semicolon. The viewer will have to say "OK" to every alert before the page will begin loading. Try it out yourself and see if you go insane. Click the link below!

Example 2

Want the code that did this? Here you go!

<HEAD> <TITLE>JavaScript Example 2</TITLE> 

<SCRIPT language="JavaScript"> <!-- alert('Please Sign My Guestbook, NOW!'); 

Page 7: Javascript Tutoriallll

alert('I mean it, NOW!!!'); alert('Did I mention I had a guestbook? Well SIGN IT!'); alert('Oh, remember....THE GUESTBOOK! O.K.?!!'); //--> </SCRIPT> </HEAD>

So, how about that? Pretty wild, isn't it? You can also use the alert with a button, so that it is not such a surprise. Place the code where you want the button to be on your page. You won't need the SCRIPT tag for this one.

<FORM> <INPUT type="button" value="Click here to see what I think of YOU!" onClick="alert('You are the greatest person I have ever met!')"> </FORM>

Give it a try. You'll be glad you did....I think.....

Now it's time to get into some really fun stuff. Yes, variables and functions. Don't worry, it's not as bad as it sounds.....let's start with declaring variables. You'll want to keep all of your variables in the HEAD section for now. Place the declarations between the SCRIPT tags inside the head section of your document.

To declare a variable in JavaScript, you will write something like this:

<HEAD> <SCRIPT language="JavaScript"> <!--hide from old browsers 

var name=value; 

//--></SCRIPT></HEAD>

Here is what these commands mean:

1. varThis indicates you are about to declare a variable.

2. nameThis is the name you give the variable. Give it any name you like (other than a JavaScript reserved word such as "function" or "onMouseover".).

3. valueThis is the initial value you want the variable to have. It can be a number, words, true, false, or null. 

Using Numbers

Page 8: Javascript Tutoriallll

You can assign a number value to a variable by placing the desired number after the = sign:

var cars=3;

You can also use a number with a decimal. JavaScript isn't too picky about whether the value is an integer or decimal. Just type it in.

var cost=9.95;

Using Strings

A string is just a group of characters, such as a sentence or a word. To define a string, you will need to place single or double quote marks around the value, like this:

var movie="The Lost World";

Also, if you place numbers inside the quotes, they are treated as a string rather than a numerical value.

Boolean Values

This one is nice. Assign the variable a value of true or false. No quotes needed. Here's an example:

var story=true;

The null Value

If you declare something as null, it means nothing. Not even zero, just plain nothing. Here's the format:

var mymoney=null;

Well, nothingness isn't so great in this case, but it can be useful when you use prompts to get information from viewers, and they type in......nothing!

Case Sensitivity

Unlike a lot of things in HTML, JavaScripts are case sensitive. So a variable named "john" is not the same as "John" or "JOHN". The same goes for commands and functions and so on. Just remember your case when you use JavaScripts, or you may get error city instead of nifty effects....

Semicolons

Don't forget those semicolons! They are used to separate JavaScript commands and declarations, and can also cause error city if they are left off. I did this a few times, and it makes for some pretty wild stuff when you try to load the page!

Functions!

Page 9: Javascript Tutoriallll

Well, functions are used to make things more organized and readable. A function is a set of JavaScript statements put together for a single purpose. You will want to keep your functions inside the SCRIPT tags inside the HEAD section. Here is the format for a function declaration:

<HEAD> <SCRIPT language="JavaScript"> <!--hide from old browsers 

function name (parameter1, parameter2) {  JavaScript Statements and declarations } 

//--> </SCRIPT> </HEAD>

1. functionIndicates that you are going to create a function.

2. nameThis is the name you give the function. As before, name it whatever you like.

3. (parameter1, parameter2) The parameters are variables that are sent to the function when it is called. You can have none, one parameter, two parameters, three parameters, and so on.

4. {This symbol lets you begin adding JavaScript statements and declarations.

5. }This indicates the end of the statements, and the end of the function. 

To make use of the function, you will make a call to the function when you want to use it. You call a function by using the name, any parameters you want to send, and a semicolon, like this:

function dosomething (mymoney, cost);

So, how does one use this stuff? Well, I'll show you another way to write the "text in the status bar" script using variables and functions. Here's the trusty old link again. Move your mouse over it, and you'll see text in the status bar. Move the mouse away, and the status bar clears.

Place your mouse here!

Now, here's the code that generated the link. See if you can work your way through it. I'll explain it at the end of the script.

<HEAD> <SCRIPT language="JavaScript"> <!--hide 

var text=" "; 

Page 10: Javascript Tutoriallll

function overlink (text) { window.status=text; } function offlink (text) { window.status=text; } 

//--> </SCRIPT> </HEAD> 

<BODY> 

<A HREF="jvar.htm" onMouseover="overlink('Functions Rule!');return true" onMouseout="offlink(' ');return true"> Place your mouse here!</A> 

</BODY>

What the...? Yes, in this case the script is much longer and takes some time to work through. Here's what the script is doing:

In the HEAD Section

1. var text=" ";This declares a variable named text, and gives it a string value of empty space.

2. function overlink(text) This declares a function named overlink. The function requires the variable text to be sent to it in order to work properly.

3. {Begins the JavaScript Statements for the function overlink.

4. window.status=text;This places the value of the variable text in the status bar. The value of text was sent to the function when it was called inside the link tag, which is the string "Functions Rule!". See the explaination of the link tag for more.

5. }Ends the statements in the function overlink.

6. function offlink (text)This declares a function named offlink. The function requires the variable text to be sent to it in order to work properly.

7.window.status=text;This places the value of the variable text in the status bar. The value of text was sent to the function when it was called inside the link tag, which is the string " ". See the explaination of the link tag for more. 

In the BODY Section

Page 11: Javascript Tutoriallll

<A HREF="jvar.htm" onMouseover="overlink('Functions Rule!');return true" onMouseout="offlink(' ');return true"> Place your mouse here!</A>

This tag calls both of the functions and passes on a string which is assigned to the variable named text. The first function, overlink, is called inside the onMouseover command. This means that when the user places their mouse over the link, the statements inside the function overlink will be executed. As you can see, overlink is called with a string variable inside the ( ) symbols. Notice we use single quotes to define this string, since double quotes are used in the onMouseover command. The string value we place here is what is sent to the function overlink, and thus is what ends up in the status bar. So, "Functions Rule!" is what shows up in the status bar when the mouse moves over the link. The onMouseout command calls the function named offlink when the mouse moves away from the link. This time, we assigned the variable text a value of blank space. The blank space is sent to the function, and is written to the status bar, erasing the "Functions Rule!" string before it. The return true phrases are there to make sure the script works by returning true.

Well, if you made it through all of that, you are ready to move on. If you still don't quite have a handle on it yet, try writing out the script on your computer, or even by hand. Sometimes it helps you work your way through the messy stuff.

Well, let's move on to some more technical stuff, in the next section: Logical Operators and Conditons. 

es, this section is for learning a bunch of operators plus the if/else statement. The first thing we'll do is go through some of the mathematical operators. Here they are:

+    addition -    subtraction *    multiplication /    division %    modulus (this is the remainder when you divide something)

Now, let's take a look at comparison operators:

>    Greater Than <    Less Than >=   Greater Than or equal to <=   Less Than or equal to ==    Equal to (remember, the "=" sign assigns a value to a variable, the "==" compares two values for equality.) !=    Not equal to

And now, the logical operators:

&&    AND ||    OR !     NOT

So, what good does this do you? Well, it'll come in handy for later scripts, as well as for the next thing we'll look at: The if/else statement.

if (conditional statement) { JavaScript statements... } 

Page 12: Javascript Tutoriallll

else { JavaScript Statements.....}

This statement is useful if you want to check for a variable value or a number of values. If the statement in side the ( ) symbols is true, the commands that follow the if command inside the { } symbols will be executed. Otherwise, the commands after the else statement are executed. Here is an example:

var number=3; var mymoney=0; if (number > 2) { mymoney=100; } else { mymoney= -100; } 

This set of code decides the fate of the variable mymoney, based on the value of the variable number. If number is greater than 2, then the value of mymoney will be changed to 100. If number is not greater than 2, the mymoney is -100, and I'm in some trouble with my bank.

Now, suppose you wanted to perform a set of commands a number of times, and end when you have what you need. To do this, you can use a for loop or a while loop to repeat things. First, the for loop:

for ( condition1; condition2; command) { JavaScript Statements.... }

OK, what this does is begin the loop with condition 1, end the loop with condition 2, and perform the command each time through. So, if you want to change a variable value 10 times, you would do something like this:

var count=1; var mymoney=0; for (count=1; count<11; count=count+1) { mymoney=mymoney+100; }

The loop begins with count=1. Then the statement mymoney=mymoney+100 is executed the first time. Then the command count=count+1 is executed, making count equal to 2. Once that is done, the value of count is checked to be sure it is less than 11 (condition 2). Since count is 2, which is less than 11, the loop statement is executed again, and count goes up to 3. This goes on and on until count is equal to 11, thus not being less than 11. The loop will end before going through another time. What did I get out of this? Well, mymoney went from 0 to 1,000 really quickly!

Now for the while loop. It does pretty much the same thing as the for loop, but is written out differently:

var count=1; var mymoney=0; 

Page 13: Javascript Tutoriallll

while (count<11) {mymoney=mymoney+100; count=count+1; } 

This example does the same thing as my last one. The only thing that is checked is whether count is less than 11 or not. If it is, the statements are executed. If not, the loop ends. Remember to add one to count within the statement section here, or you'll get the ever popular "infinite loop".

So, why all the technical stuff? Well, it will help you better understand some more complicated scripts.....and you could just go off and write some stuff! The next section uses a script with an if/else statement....so let's check it out! JavaScript Prompts. 

Well, let's say you wanted to get somebody's name before they saw the page, and then write their name on your page right before their very eyes.......Well, you can do this using a javascript prompt. Here's the command:

prompt('Your Question', ' ');

This will bring up a window asking the question of your choosing, with a space for the viewer to answer. The second set of quotes allows you to enter a default answer. If you leave it blank, the viewer will just see an empty box ready to be typed in. This is usually done before the page loads, so that you can write the answer they give into your page. To view an example, click the link below. You will get a prompt for your name, and your name will be written on the page!

Example 3

Now, for the script that made this work. Note how the prompt and if/else statements are in the HEAD section, while the actual writing of the name occurs in the BODY section.

<SCRIPT language="JavaScript"> <!--hide var yourname= prompt('Please enter your name, so you can get a special greeting', ' ');

if ( (yourname==' ') || (yourname==null) ) { yourname="Dude"; }

//--> </SCRIPT>

</HEAD>

<BODY>

<SCRIPT language="JavaScript"> <!--hide document.write("<CENTER><H1>Hello, " + yourname + " ! Welcome to My Page! <\/H1><\/CENTER>");

//-->

Page 14: Javascript Tutoriallll

</SCRIPT>

</BODY>

The first thing that happens is that the variable yourname is assigned the value it receives from the user from the prompt. So the variable yourname will be a string of characters that makes up the person's name. The if/else statement assigns yourname a value of "Dude" if nothing is entered in the prompt by the user. It checks for " " and for null, and both are pretty much nothing. Now, in the BODY section, you again use the SCRIPT tags to set off the JavaScript from any HTML around it. You will also see a new command called document.write(" "); . This is what allows the JavaScript variable yourname to be written onto the HTML document. You are writing two strings plus your variable, yourname. The variable yourname is not in quotes because it is a value and not itself a string (it's value is a string). That's why we have the plus signs around it....It makes the browser write the first string plus the variable plus the second string. Now, notice the HTML tags are inside the strings! Since this is a javascript, the only way to write the HTML tags back to the page is by including them inside the quotes as part of the string. Also, you probably noticed the way the closing tags were written differently. (<\/H1>). The backslash is there as the javascript escape character. It allows you to write the forward slash without it being mistaken for a division sign! (Remeber / is division in JavaScript). Thus using the backslash followed by a forward slash ultimately gives us.......our single forward slash. Pretty nifty trick, isn't it?

Well, that does it for now. Let's go check out the next section, JavaScript Passwords. 

OK, I finally got around to writing the javascript password protection tutorial. You will see the example script here is pretty straightforward, but it is also pretty easy to get around. I'll tell you why and give you links to more secure scripts later in this tutorial.

Warning: These scripts are not totally secure and your page can be seen if someone gets through. Do NOT protect anything important with a script like this. Try looking for aCGI Script or ask your web host to set up an .htpassword file if you need to protect something important.

Below is a link that will show you an example of what we are about to create. Click the link. When you are prompted for a password, enter:

cool

Example Password Protected Page

OK, if you typed "cool" into the prompt, you were allowed to continue loading the example page. If you typed anything else or nothing at all, you were taken right back to this page. That is pretty cool. Now let's see the script that makes this work. You would place this script in the HEAD section of the page you want to protect. In this case, it was "jex8.htm". Here is the script:

<HEAD><SCRIPT language="JavaScript"><!--hide

var password;

var pass1="cool";

password=prompt('Please enter your password to view this page!',' ');

if (password==pass1)

Page 15: Javascript Tutoriallll

alert('Password Correct! Click OK to enter!');else { window.location="http://www.pageresource.com/jscript/jpass.htm"; }

//--></SCRIPT></HEAD>

If you have been through the previous tutorials, most of the code will make sense to you. Let's get to the details of what is going on with this thing:

var password;This creates a variable named "password".

var pass1="cool";This creates a password that will be accepted by the script. We name it pass1 in case we would like to have more than one acceptable password. ( ie pass2, pass3 etc. ).

password=prompt('Please enter your password to view this page!',' '); This is what creates the prompt for the user to enter a password. Whatever the user enters in the prompt will be the value of the variable "password". If you have not seen prompts before, go to the prompts tutorial for more info.

if (password==pass1) alert('Password Correct! Click OK to enter!'); This is where we verify the password. The variable "password" is what the user just typed into the prompt. The variable "pass1" is the only password we will accept. If they are the same, we send them an alert that the password was OK and they can continue. If you haven't seen if/else statements yet, go to the if/else page. For more on alerts, see the alerts page.

else { window.location="http://www.pageresource.com/jscript/jpass.htm"; } This is what happens when they type in an incorrect password. We send them to a page of our choice. In IE4, it looks like nothing happened, it just reloads this page. In NS3 and 4 you will probably see the protected page for a quarter of a second. I said it wasn't the most secure script out there, so I would recommend the links at the end of the tutorial so you can get a more secure script. I chose to send it back to this page (jpass.htm), but you can type any url here you want. Maybe you could use something like: window.location="http://www.barbie.com"; Make them cringe a little.......

All that's left after that is to link to the protected page from another page, like my link above to the example. No problem.

Now, if you want more than one acceptable password, you can make a couple of modifications and you will have it.

First, add more variables for the accepted passwords. If you want three good passwords, declare three variables. Since I had one named "pass1" already, I will just use "pass2" and "pass3":

Page 16: Javascript Tutoriallll

var pass1="cool";var pass2="awesome";var pass3="geekazoid";

Next, you will need to change your "if" statement to include the other two passwords. This is done with the || (or) operator:

if (password==pass1 || password==pass2 || password==pass3) alert('Password Correct! Click OK to enter!');

This means that if the user typed in the correct value for "pass1" OR "pass2" OR "pass3", the password is correct and they can view the page.

Here is how the full code would look for this:

var password;

var pass1="cool";var pass2="awesome";var pass3="geekazoid";

password=prompt('Please enter your password to view this page!',' ');

if (password==pass1 || password==pass2 || password==pass3) alert('Password Correct! Click OK to enter!');else { window.location="http://www.pageresource.com/jscript/jpass.htm"; }

If you want to see this in action, click the link for this example below. Enter one of the three correct passwords (cool, awesome, or geekazoid) and you will see the next page!

Multiple Password Example

So, why is it easy to hack the script? One way is for the viewer to disable javascript. Not only will they get to the page this way, they can also view the source code to see the passwords and use them later. Thus, if you are protecting something important, you should use something more secure. You can find some more secure password javascripts at The JavaScript Source. You can also look for a CGI password script at The CGI Resource Index.

Well, that was OK, but if you go to the next section you will see a slightly better version of this same script. So, go on toPassword Protection 2! 

In the last section, I introduced javascript password protection, but the script had a slight problem: Netscape browsers would show the protected page momentarily even if the password was incorrect. In this section, I will show you the same script, but the difference is that it will use an intermediate page so that the protected page is not displayed.

Warning: These scripts are not totally secure and your page can be seen if someone gets through. Do NOT protect anything important with a script like this. Try looking for aCGI Script or ask your web host to set up an .htpassword file if you need to protect something important.

Page 17: Javascript Tutoriallll

Now that I have said that so boldly, let's take a look at how this version of the script works. Try out the example below:

Click to Enter

A little better, I suppose. Let's take a look at the code you will need:

1)    You will need to place a link to the intermediate page on one of your pages. In my example, the intermediate page is "jex10.htm". I put the link on this page, "jpass2.htm". Example below:

"jpass2.htm"

<BODY><A HREF="jex10.htm">Click to Enter</A></BODY>

2)    Now you need to create your intermediate page. In my case, this is "jex10.htm". You will need the following script on this page:

"jex10.htm"

<HTML><HEAD><TITLE>Intermediate Page</TITLE><SCRIPT language="JavaScript"><!--hidevar password=prompt('Enter the password:','');var mypassword="cool";if (password==mypassword){ window.location="jex11.htm";}else{ window.location="jpass2.htm";}//--></SCRIPT></HEAD><BODY>&nbsp;</BODY></HTML>

This intermediate page is what does all the work. As you can see, if the password is correct, it takes the user to the protected page. In the example, the protected page was "jex11.htm". You can replace that with the url of the page you wish to protect.

If the password is incorrect, the user gets sent back to the page that contains your link to the intermediate page. In my case, that is the very page you are looking at, "jpass2.htm".

Page 18: Javascript Tutoriallll

Well, give it a try and see if it works better for you. Have fun!

So, why is it easy to hack the script? One way is for the viewer to disable javascript. Not only will they get to the page this way, they can also view the source code to see the password and use it later. Thus, if you are protecting something important, you should use something more secure. You can find some more secure password javascripts at The JavaScript Source. You can also look for a CGI password script at The CGI Resource Index.

Ready for a new subject? Well, then go to the next section: Confirmation Boxes. 

A javascript confirmation box can be a handy way to give your visitors a choice of whether or not an action is performed. A confirmation box will pop up much like an alert box, but will allow the viewer to press an "OK" or "Cancel" button. Here is the basic command for creating a confirmation box:

confirm("Text or question you want to use");

The trouble is, if you use just that it isn't very useful. The confirmation box will return a value of true or false, so this is what we must use to make use of the confirmation box. An easy way to get the value for later use is to assign it to a variable, like this:

var where_to= confirm("Do you really want to go to this page??");

Now, you can use the where_to variable to send the user to one page or another, depending on the value the confirmation box returned. You can do this with an if/else block:

if (where_to== true) { window.location="http://yourplace.com/yourpage.htm"; }else { window.location="http://www.barbie.com"; }

In this case, if the viewer hits the "OK" button, the browser will go to your special page. If the viewer hits the cancel button, the browser takes the viewer on a fun trip to the Barbie web site!

To make use of it though, you'll probably want to write a JavaScript function in your head section that you can call in the body of the page. You could place the items above into a function like this, to go inside your head tags:

<SCRIPT language="JavaScript"><!--function go_there(){ var where_to= confirm("Do you really want to go to this page??"); if (where_to== true) { window.location="http://yourplace.com/yourpage.htm"; } else { window.location="http://www.barbie.com"; }

Page 19: Javascript Tutoriallll

}//--></SCRIPT>

Now, you need to find a way to call the function inside the body of your document so that you can offer the viewer access to the special page. You can use a button to call the function when it is clicked, so you would place something like this in the body section:

To go to my special page, click the button below:<BR><FORM><INPUT TYPE="button" value="Go!" onClick="go_there()"></FORM>

This would work like the example button below, give it a try!

To go to my special page, click the button below: 

As you can see, this may come in handy for something you want to code down the line. Of course, I can't confirm that...

Well, that does it for now. Let's go check out the next section, Browser Detection with JavaScript. 

Browser detection allows you to find out what browser your viewer is using, and then perform a script based on it-- or just to send a friendly message to those with your favorite browser.

There are two objects often used for this, the navigator.appName and navigator.appVersion objects. The first one returns the name of the browser, the second returns the version of the browser.

If the browser is Netscape, navigator.appName returns the string "Netscape". If it is Internet Explorer, it returns the string "Microsoft Internet Explorer". Using just this, you could make a script to alert people as to what browser they are using (just to bug them). Like this:

<HEAD><SCRIPT language="JavaScript"><!--var browserName=navigator.appName; if (browserName=="Netscape"){ alert("Hi Netscape User!");}else { if (browserName=="Microsoft Internet Explorer") { alert("Hi, Explorer User!"); } else { alert("What ARE you browsing with here?"); }}//--></SCRIPT>

Page 20: Javascript Tutoriallll

</HEAD>

You can do the same thing with the navigator.appVersion, except you will most likely want to grab just the integer from the version information (2,3,4, etc.). To do this, we use the parseInt() function:

var browserVer=parseInt(navigator.appVersion);

Now, it returns only the integer value and not something like version 4.51. It just sends back 4 in that case. Thus, we could alert viewers as to whether their browser is new enough for us or not:

<HEAD><SCRIPT language="JavaScript"><!--var browserVer=parseInt(navigator.appVersion); if (browserVer >= 4){ alert("Your browser is new enough for my site.");}else{ alert("I think you need a new browser!");}//--></SCRIPT></HEAD>

Of course, you can use both objects to be more exact. You could look for a certain set of browsers and only if they are above a certain version:

<HEAD><SCRIPT language="JavaScript"><!--var browserName=navigator.appName; var browserVer=parseInt(navigator.appVersion); if ((browserName=="Netscape" && browserVer>=3) || (browserName=="Microsoft Internet Explorer" && browserVer>=4)) version="n3"; else version="n2";

if (version=="n3") alert("Your browser passes the test");else alert("You need an upgrade, I think.");//--></SCRIPT></HEAD>

As you can see, that uses a lot of the logical operators from a previous section. It is basically saying that "if the browser name is Netscape and it is version 3 or greater, OR if the browser name is Microsoft Internet Explorer and the version is 4 or greater, then we will assign the variable version as 'n3'. Otherwise, it is going to be 'n2.' Then we move on to the rest."

One of the more common uses for browser detection is to redirect a viewer to a page made for his/her browser type or browser version. We will discuss that in the next section on redirection.

Page 21: Javascript Tutoriallll

Well, that does it for now. Let's go check out the next section, Redirection with JavaScript. 

Note: Be careful using this if the page you use it on is listed in a search engine. Many of them find redirection to be a way of attempting to spam their index, and may remove the site from the listings. If you are unsure, don't try this-- or contact the search engine for their rules.

Redirection is often used to take viewers to a page depending on their browser's name or version. To redirect a viewer instantly, you just need to add a short command in your head section:

<HEAD><SCRIPT language="JavaScript"><!--window.location="http://someplace.com";//--></SCRIPT></HEAD>

This would take the viewer right to the url you used as soon as they start loading the page. Sometimes this is done if a site has moved to another location. Another use for it is to detect a browser type and redirect your viewers to one page for Netscape, another of Internet Explorer, or a third for other browsers:

<HEAD><SCRIPT language="JavaScript"><!--var browserName=navigator.appName; if (browserName=="Netscape"){ window.location="http://www.someplace.com/ns.html";}else { if (browserName=="Microsoft Internet Explorer") { window.location="http://www.someplace.com/ie.html"; } else { window.location="http://www.someplace.com/other.html"; }}//--></SCRIPT></HEAD>

This uses the browser detection method from the previous section. Rather than popping up an alert box, we redirect the viewer to a page that best suits the browser being used.

If you want to have one page for version 4 browsers and another for others, we can take another script from the previous section and change it in the same way:

<HEAD><SCRIPT language="JavaScript"><!--var browserVer=parseInt(navigator.appVersion); if (browserVer >= 4)

Page 22: Javascript Tutoriallll

{ window.location="http://www.someplace.com/v4.html";}else{window.location="http://www.someplace.com/other.html";}//--></SCRIPT></HEAD>

Not too bad, the only trouble is the need to create so many pages!

You can also use this to help people who come into your site, but come in on a page that should be within a frameset that you use for navigation. Using the top.frames.length object, you can find out if the page is in a frame or not. If the value is zero, the page is not in a frame. If it is greater than zero, the page is inside a frame. So, you could take the viewer back to your main frameset page using a script like this:

<HEAD><SCRIPT language="JavaScript"> <!-- function getgoing() { top.location="http://someplace.com"; } if (top.frames.length==0) { alert("You will be redirected to our main page in 10 seconds!"); setTimeout('getgoing()',10000); }//--> </SCRIPT> </HEAD>

This will alert the viewer and take them to the main page after 10 seconds. You can change the number in the setTimeout function to adjust the time if you like.

You can also use it to break a viewer out of someone else's frames if they followed a link that didn't have the target set correctly. It uses the same idea in reverse:

<HEAD><SCRIPT language="JavaScript"> <!-- function getgoing() { top.location="http://someplace.com"; } if (top.frames.length > 0) { alert("The frames will be broken in ten seconds."); setTimeout('getgoing()',10000); }//-->

Page 23: Javascript Tutoriallll

</SCRIPT> </HEAD>

As you can see, redirection can be a handy tool at times. Just use it with caution if you are worried about the search engines.

Well, that does it for now. Let's go check out the next section, New Windows with JavaScript. 

To open a new window, you will need to use yet another ready-made JavaScript function. Here is what it looks like:

window.open('url to open','window name','attribute1,attribute2')

This is the function that allows you to open a new browser window for the viewer to use. Note that all the names and attributes are separated with a comma rather than spaces. Here is what all the stuff inside is:

1.'url to open'This is the web address of the page you wish to appear in the new window.

2. 'window name'You can name your window whatever you like, in case you need to make a reference to the window later.

3. 'attribute1,attribute2'As with alot of other things, you have a choice of attributes you can adjust. 

Window Attributes

Below is a list of the attributes you can use:

1. width=300Use this to define the width of the new window.

2. height=200Use this to define the height of the new window.

3. resizable=yes or noUse this to control whether or not you want the user to be able to resize the window.

4. scrollbars=yes or noThis lets you decide whether or not to have scrollbars on the window.

5. toolbar=yes or noWhether or not the new window should have the browser navigation bar at the top (The back, foward, stop buttons..etc.).

6. location=yes or noWhether or not you wish to show the location box with the current url (The place to type http://address).

7. directories=yes or noWhether or not the window should show the extra buttons. (what's cool, personal buttons, etc...).

Page 24: Javascript Tutoriallll

8. status=yes or noWhether or not to show the window status bar at the bottom of the window.

9. menubar=yes or noWhether or not to show the menus at the top of the window (File, Edit, etc...).

10. copyhistory=yes or noWhether or not to copy the old browser window's history list to the new window. 

All right, here's an example code for opening a new window:

<FORM> <INPUT type="button" value="New Window!" onClick="window.open('http://www.pageresource.com/jscript/jex5.htm','mywindow','width=400,height=200')"> </FORM>

Test it out below:

Yes, you got a 400 by 200 window with some writing in it!

Some Important Rules

Before we move on, we need to make note of some things so you won't go insane like I did trying to get this to work right!

1. When you get to the INPUT tag, keep everything in that tag on one single line in your text editor, including the javascript commands. (The text goes to the next line on this page so you can print it out easily).

2. Once you come to the onClick=" ", don't leave any spaces between anything. Just use the commas and the quote marks. Any white space will keep it from working correctly in Netscape.

3. Don't put quote marks around the yes, no, or numbers for the attributes. You only use single quotes around the entireset of attributes.

4. In some browsers, you may need to substitute the number 1 for yes, and the number zero for no in the attributes section. The yes or no should work fine, though. 

A New Browser Window

Okay, enough rules. Let's look at the code that makes a completely new browser! Basically, you just use yes for all of the attributes. Here is the code:

<FORM> <INPUT type="button" value="New Window!" onClick="window.open('http://www.pageresource.com/jscript/jex5.htm','mywindow','width=400,height=200,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes')"> </FORM>

Page 25: Javascript Tutoriallll

Give it a try, this window has all the features!

Remember, keep everything on one line....one really, really long line! I just put the sample code on new lines so you wouldn't have to scroll forever to read everything........and your printer won't go crazy now either!

Closing a New Window

Hmm.....what's with the "Close Window" button you saw in the new window? How does one do do that? To use that trick, use the window.close() function in the HTML of the new window. Just put this code wherever you want the close button to show up in the new window:

<FORM> <INPUT type="button" value="Close Window" onClick="window.close()"> </FORM>

Of course, the window can be closed with the "x" symbol on the top-right of the window as well.

Set the Window Position

There is another set of options you can use to set the position of the new window on the viewers, but it only works withNS4+ and IE4+:

1. screenX=number in pixelsSets the position of the window in pixels from the left of the screen in Netscape 4+.

2. screenY=number in pixelsSets the position of the window in pixels from the top of the screen in Netscape 4+.

3. left=number in pixelsSets the position of the window in pixels from the left of the screen in IE 4+.

4. top=number in pixelsSets the position of the window in pixels from the top of the screen in IE 4+. 

Great, but how do you decide which commands to use if there are different ones for each browser? In this case, you can use both sets of commands- the browser will ignore the set it does not recognize. The example below will give you a new window 0 pixels from the left and 100 pixels from the top of your screen:

<FORM><INPUT type="button" value="New Window!" onClick="window.open('jex5.htm','mywindow','width=400,height=200,left=0,top=100,screenX=0,screenY=100')"> </FORM>

Now, that is a lot of work- but you can now customize a new window for your viewers!

Well, that's all for now.....The next section is: Using Link Tags for JavaScripts. 

Page 26: Javascript Tutoriallll

I get this question so much, I figured I'd better get in gear and write another section to address using the link tag for javascripts (such as new windows), rather than using the old grey button. Well, there are a couple of ways to do this. I'll start with the easier to understand version first.

The first method is to access a javascript function within the HREF attribute of your link tag. So, if you want to link to another page, you normally write:

<A HREF="nextpage.htm">Click here</A>

Well, you can access a javascript function you have written instead by writing the link this way:

<A HREF="javascript:myfunction()">Click Here</A>

Yes, now you can open that new window without using the grey button. Here is a script to give you the new window:

First, I found that this works much better if you create your own function in the head section first. All this function needs to do is open your new window. So, in your head section, create a function like this:

<HEAD> <SCRIPT language="JavaScript"> <!--hide 

function newwindow() { window.open('jex5.htm','jav','width=300,height=200,resizable=yes'); } //--> </SCRIPT>

The above script will open my "jex5.htm" page in a new window. As you know, replace this with url of the page you wish to open, and adjust the other attributes to your liking. If you need to know more about the window.open function, see theOpening a New Window tutorial and learn that first.....then come back and get going with the rest of this section.

Now go into your body section to wherever you want the link to appear, and write your link tag this way:

<A HREF="javascript:newwindow()" >Click Here!</A>

Now you will get a link like the one below. Give it a try and see the new window appear when you click the link!

Click Here!

For those of you who want to use an image for the link, just do the normal "image inside the link tag" trick, but with the link tag modified for javascript like above:

<A HREF="javascript:newwindow()" ><IMG SRC="scare.jpg" border="0"></A>

Now you can click on the image below for a new window!

Page 27: Javascript Tutoriallll

The second way to do this is a little more difficult, but some people may be more comfortable with it. The trick is to go ahead and use the onClick=" " attribute in your link tag. The trick here is to keep the browser from following the actual link after running your script. Here is a sample of using the onClick attribute in the link tag:

<A HREF="newpage.htm" onClick="newwindow();return false">Click Here!</A>

I used the same script we had written in the head section for the first method, but I used it inside the onClick=" " command. Also notice the semicolon after the function call, and the "return false" at the end of the command. The return false part keeps the browser from going to "newpage.htm" after opening your new window. You could put any page here you want, and the link will no longer take you there (except in some older browsers). So you don't really have to put an actual url in the HREF attribute here unless you wish to offer an alternative for those with older browsers that don't recognize the onClick=" " command. As in the above example, you can also use an image inside your link tag to make a clickable image. Below is an example link where I used this second method:

Click Here!

Well, that about does it for now......The next section is a Congratulations Section! 

So, you want to set things to happen after a certain amount of time? Well, the setTimeout function can help you create some nice scripts that will use time delays to make things happen. Let's take a look at how to call the setTimeout function:

setTimeout("yourfunction()",1000);

The first parameter is a string, which is going to be the function you want to use. This function was named "myfunction()". The second parameter is a number. This number is going to be the number of milliseconds the browser should wait before executing your function. Above, we have 1000 milliseconds, which will be 1 second.

Now, what can you do with it? Let me start with an example that shows you the setTimeout function in action. Click the button to the right of the text box below and watch what happens!

    

Now, how did I get that text to change a second time while you were able to just watch? Let's look at the script for this trick:

<HEAD><SCRIPT language="JavaScript"><!--hidefunction newtext(){ document.myform.mytext.value="Hey! I have changed!"; setTimeout("moretext()",1000);

Not Much Here.

Page 28: Javascript Tutoriallll

}function moretext(){ document.myform.mytext.value="I just change with the time!";}

//--></SCRIPT></HEAD>

<BODY><FORM name="myform"><INPUT type="text" name="mytext" value="Not Much Here." size="30">&nbsp;&nbsp;<INPUT TYPE="button" name="but1" value="Click!" onClick="newtext()"></FORM>

We use the HEAD section to define our two functions. The first function is named "newtext()". We call this function when the user clicks the button we created. As you can see, we changed the value of the text in the text box by using the name of the form and the name of the textbox:

document.myform.mytext.value="Hey! I have changed!";

The next command is what makes the second change happen. We call the function "moretext()" after 1000 milliseconds:

setTimeout("moretext()",1000);

Now, the function "moretext()" changes the value in the form box one more time, after waiting 1 second:

document.myform.mytext.value="I just change with the time!";

Now, in the BODY section, we simply put the code for the form and the textbox. Remember to give your form and your textbox names. That is how we are able to change the text in the box using the functions. The name for the form above was "myform", and the name of the text box was "mytext".

If you need more help on how to access form elements, see the tutorial Beginning with Forms.

Now you know how to call another function of your choice after a certain amount of time. This will allow you to create some pretty fun scripts. Well, the next section is on JS Arrays! 

Arrays are one way of keeping a program more organized. They allow you to do some things that are difficult without them. Arrays are usually a group of the same variable type that use an index number to distinguish them from each other. Suppose you wanted to write out 5 quotes, and use variables for each one of the quotes. You could define 5 variables:

quote1="I like JavaScript."; quote2="I used to like Java."; quote3="JavaScript rules."; quote4="Help! JavaScript Error!"; quote5="Just Kidding.";

Page 29: Javascript Tutoriallll

However, a better way may be to use an array. To define an array, we need to follow the following form:

var Name_of_Array= new Array(number_of_elements);

Name_of_Array would be the name you want to give the array variable, the number_of_elements is the number of variables you want the array to store. So, for our quotes, we could write:

var quote= new Array(5);

Now, to assign values, we are going to use what is called an index number, and place it inside brackets. We attach this right on the end of the word quote, so our first quote would be:

quote[0]

I know, zero instead of 1. Arrays just work that way, the first element is always zero and the last element is always one less than what you define as the number of elements. In this case, our first element is quote[0], the last is quote[4]. So to assign the values we had, we could use a straight assignment, like this:

var quote= new Array(5) quote[0]="I like JavaScript."; quote[1]="I used to like Java."; quote[2]="JavaScript rules."; quote[3]="Help! JavaScript Error!"; quote[4]="Just Kidding.";

Notice that when we do this, we leave off the semiclon at the end of the array definition, and use semicolons at the end of each element we define.

So far, it has only made things more complicated. However, this array can now be used as part of a loop, using the value of the index numbers as a variable:

var x=0; for (x=0; x<5; x++) { alert(quote[x]); }

This uses the variable x in place of each index number, and runs the alert for all 5 elements in our array. The first time through, you would get an alert with quote[0], the second time, quote[1], and so on. If you need more on for loops, see the conditional tutorial.

I may not have explained the ++ operator before. x++ means that we add one to the value of x. In a similar fashion, we can subtract one from x with x--. This is how we are able to go from x being 0 to x being equal to 4. It stops at 4 because part of the condition is that the loop is only run while x is less than 5. So the last time it runs, x is equal to 5 and it does not go any further.

The script in action is a bit annoying. You can write this script in the head section. We will make this into a function, and call it from a link (the link must be in the body):

<HEAD> <SCRIPT language="JavaScript"> <!-- 

Page 30: Javascript Tutoriallll

function display_quote() { var quote= new Array(5) quote[0]="I like JavaScript."; quote[1]="I used to like Java."; quote[2]="JavaScript rules."; quote[3]="Help! JavaScript Error!"; quote[4]="Just Kidding."; var x=0; for (x=0; x<5; x++) { alert(quote[x]); } } //--></SCRIPT> </HEAD> <BODY> <A HREF="javascript:display_quote()">Click Here, I dare you!</A> </BODY>

Here, try it out. Just don't get angry!

Click Here, I dare you!

You could also assign the values of the array using a loop. This would allow the viewer to assign the values using prompts, and then you could alert them with their own words!

var quote= new Array(5); var y=0; for (y=0; y<5; y++) { quote[y]=prompt('Enter a Quote!',' '); } 

Notice that we just defined the array, without assigning initial values. Don't forget the semicolon! Then we get the values by letting the viewer enter them through a prompt. quote[y] uses the value of y each time it is run. So, you are assigning quote[0] the first time, quote[1] the second time, and so on. The complete script is below, and it is even more annoying than the other one!

<HEAD> <SCRIPT language="JavaScript"> <!-- function display_quote2() { var quote= new Array(5); var y=0; for (y=0; y<5; y++) { quote[y]=prompt('Enter a Quote!',' '); } var x=0; for (x=0; x<5; x++) { alert(quote[x]); 

Page 31: Javascript Tutoriallll

} } //--></SCRIPT> </HEAD> <BODY> <A HREF="javascript:display_quote2()">Click Here, I dare you!</A> </BODY>

Here, try it out. Drive yourself insane...

Click Here, I dare you!

The examples here could annoy people, but they do show you how arrays can be useful. There are certainly more useful ways to use them! I know you can think of a few...

Well, that does it for now, Let's go on to the next section, Associative Arrays. 

Associative arrays give you another way to store information. Using associative arrays, you can call the array element you need using a string rather than a number, which is often easier to remember. The downside is that these aren't as useful in a loop because they do not use numbers as the index value.

An associative array is defined just like a regular array, but we insert some text in the place we had numbers in the regular arrays:

var my_cars= new Array()my_cars["cool"]="Mustang";my_cars["family"]="Station Wagon";my_cars["big"]="SUV";

Now we can get the Word Mustang later in the script by remembering it is the "cool" car, so we would use my_cars["cool"]. This could be used to prompt a user to input the type of car he/she would prefer. Then you can send back what you think the viewer should buy based on the input:

<SCRIPT language="JavaScript"><!--function which_car(){var my_cars= new Array()my_cars["cool"]="Mustang";my_cars["family"]="Station Wagon";my_cars["big"]="SUV";

var car_type=prompt("What type of car do you like?","");

if ((car_type=="cool") || (car_type=="family") || (car_type=="big")) alert("I think you should get a(n) "+my_cars[car_type]+".");else alert("I don't really know what you should get. Sorry.");}//--></SCRIPT><FORM>

Page 32: Javascript Tutoriallll

<INPUT TYPE="button" onClick="which_car()" value="Go!"></FORM>

You can try it out with the button below. Of course, most of the time you will end up with the "I don't know" answer-- unless you happen to type in one of the three car types we used!

Well, that should take car of associative arrays for now. Try them out and see what kind of ideas you can come up with to make some useful scripts!

Well, that does it for now, Let's go on to the next section, Preloading Images. 

Preloading images is a technique often used in Rollover Effects or other image scripts which work more quickly when the images for them are loaded as soon as possible.

What javascript does is allow you to start loading the images in the HEAD section of your page, which means that with this technique (unless the images are large or great in number) your viewers will have the necessary images in their browser's cache before the script starts to run. This way, an image rollover will be less likely to make the viewers wait for the browser to download the second image, because it is in their browser's cache.

To get this going, you need to have a small section of script in the HEAD section of your page. Here is a sample of a script that preloads a single image:

<SCRIPT language="JavaScript"><!--pic1= new Image(100,25); pic1.src="http://someplace.com/image1.gif"; //--></SCRIPT>

The first command defines a new image object, giving it a width of 100 and a height of 25. You would replace these with the width and height of your image. The second defines the url or web address of the image. You would replace this with the url of your image. Not too bad now, is it?

However, there is a chance your viewer will come through with an older browser which doesn't support the image object. So, to be on the safe side you may wish to implement a form of Browser Detection or Object Detection to keep from giving the older browsers a javascript error. I will use the shorter one here, which is object detection. For more on object detection, see the tutorial on what it can do.

Here, we want to know if the image object exists, which in javascript is "document.images". So, we just need to check for it with an if condition, and then run the preloading code:

<SCRIPT language="JavaScript"><!--if (document.images){ pic1= new Image(100,25); pic1.src="http://someplace.com/image1.gif"; }//--></SCRIPT>

Page 33: Javascript Tutoriallll

There, now you have the code to preload (what a rhyme!). If you want to do this for multiple images, just be sure to assign them a different name-- such as pic2, pic3, and so on. Adjust your width, height, and urls accordingly. You will have two lines for each image. For example, to preload three images, you would use a code like this:

<SCRIPT language="JavaScript"><!--if (document.images){ pic1= new Image(100,25); pic1.src="http://someplace.com/image1.gif";

pic2= new Image(240,55); pic2.src="http://someplace.com/image2.gif";

pic3= new Image(88,31); pic3.src="http://someplace.com/image3.gif"; }//--></SCRIPT>

In the next section you will see an example of how preloading works with the image rollover script. The first section will use browser detection, while the following sections will use object detection like we did here.

Well, that does it for now, Let's go on to the next section, JS Rollovers. 

Previous

By: John Pollock

Next

Using a javascript to change an image when someone moves their mouse over it has become quite popular. I've heard it called many things: "hover buttons", "rollover", and "image highlighter" are a few. What happens is that we use two images, a link, and a javascript to make a clickable image link that is "highlighted" when a mouse passes over it.

To begin, you will need to make yourself two images of the same size, making whatever changes you would like to the second one. Below is an example where I chose to make an image with blue text and one in red text. The red-text image is what I want people to see when they move their mouse over the blue-text image.

OK, that is the easy part. Now we have to have a script that will do all the work for us. I'm going to go ahead and put the whole thing below, and explain the script in parts afterward. I got this script from a free script page, did some formatting for readability, changed some variable names, and added a check for the image object. Here is the code for the HEAD section of your page:

Page 34: Javascript Tutoriallll

<HEAD> <SCRIPT language="JavaScript"><!--

if (document.images) { pic1on= new Image(100,25); pic1on.src="shoes2.gif";

pic1off= new Image(100,25); pic1off.src="shoes1.gif"; }

function lightup(imgName) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; } }

function turnoff(imgName) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; } }

//--></SCRIPT></HEAD>

Part 1: Browser CheckAll right, the first step is to check for a browser that supports all the functions and declarations we will be using. This is done with Object Detection:

if (document.images){ statements (see code above/explanation below)}

This checks to ensure the browser supports the image object before it preloads the images. This way, you can avoid javascript errors in older browsers.

Part 2: Define and Load Your ImagesNow, we get the images involved in the scheme here:

if (document.images) {

Page 35: Javascript Tutoriallll

This checks to ensure the browser supports the image object.

pic1on= new Image(100,25);

This defines a new image called "pic1on" with a width of 100 and a height of 25.

pic1on.src="shoes2.gif";

This gives the source, or url of the image. This allows it to load now so users don't wait for a new image to load when they pass their mouse over it later. Be sure this is the url of your 2nd image. This is the one you want people to see when their mouse passes over.

pic1off= new Image(100,25);

Now you define your default, or 1st image. pic1off.src="shoes1.gif";

Give the url of your default image so it is loaded.

} : Ends the image defining and loading statements.

Function 1: The mouseover FunctionNow we get to the function that will be triggered by the mouse moving over the image:

function lightup(imgName){

This defines a function named "lightup". It is reading in a parameter called "imgName". "imgName" is going to be the name="pic1" attribute of the 2nd image from our HTML document. It is sent to this function when we call it later in the HTML document (see below). imgName turns out to be "pic1". The "{" begins the group of statements for the function.

if (document.images) {

Another check and beginning of statements for browsers with the image object.

imgOn=eval(imgName + "on.src"); This defines the variable "imgOn" as the sum of the variable "imgName" and the string "on.src". Remember, the function read in "imgName" as "pic1", so the sum ends up as "pic1on.src", which is defined earlier as the url of our 2nd image.

document[imgName].src= imgOn;

Now, we define imgOn for the document, so it loads the correct image. By substituting what we got for imgOn a moment ago, and substituting "pic1" for imgName (which was sent to the function), we get this:

document[pic1].src=pic1on.src.

This is why we need to use the name="pic1" attribute in the image tag in our HTML later. This makes a reference to an image in the document by the name of "pic1". The new source (url) for the image is now the value of "pic1on.src", which we defined earlier as "shoes2.gif", our 2nd image. A bit complicated at first, but it works out nicely, doesn't it?

Page 36: Javascript Tutoriallll

} } : These end the "n3" statements and the function statements.

Function 2: When the Mouse Leaves the Image

function turnoff(imgName) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; } }

//---->

</SCRIPT></HEAD>

This function does the same thing as the last one, except that it occurs when the mouse moves off the image. Thus, I named the function "turnoff" since it turns the previous function "off" and returns to the 1st image. After the function ends, the script and HEAD tags are closed.

Finally, the HTML!Now, go down into your BODY section and find out where you would like your image to go. You will then put in the following linked image code. You should place everything on one line, I have it this way only for readability.

<A HREF="index.html" onMouseover="lightup('pic1')" onMouseout="turnoff('pic1')"> <IMG SRC="http://www.pageresource.com/images/shoes1.gif" name="pic1" width="100" height="25" border="0"></A>

Notice how we call our function "lightup" with the parameter 'pic1' on the Mouseover. We then call the function "turnoff" with the parameter 'pic1' on the Mouseout. The action is all done in our link tag. You can link to any url you wish here, and that will be where the user goes if they click the image. In the image tag, use your first (default) image as the image source. Also, be sure you use the name="pic1" attribute, as well as defining your height and width. This will make sure the script knows the name, height, and width of your image and will run smoothly. The border attribute is up to you. I chose zero for mine because I wanted the image to look like text.

The Final Product: A Changing, Linked Image

 

Yes, there it is. Move your mouse over it and see the text turn red! You can click it if you want, but you'll end up back at the main JavaScript Page......

But I Want to do this for Multiple Images!No problem. You can use it for as many images as you wish. Just be sure to define your other images along with your first. Remember, you need two images for every one you want to change. To add extras, define them first back in the script in the HEAD section:

Page 37: Javascript Tutoriallll

if (document.images) { pic1on= new Image(100,25); pic1on.src="http://www.pageresource.com/images/shoes2.gif"; pic2on= new Image(100,25); pic2on.src="http://www.pageresource.com/images/story2.gif";

pic1off= new Image(100,25); pic1off.src="http://www.pageresource.com/images/shoes1.gif"; pic2off= new Image(100,25); pic2off.src="http://www.pageresource.com/images/story1.gif"; }

Now, be sure you name it correctly in the HTML in the BODY section. For the new image here, we will name it "pic2". (For more, just use "pic3", "pic4", and so on). Then just link it to another page:

<A HREF="newpage.html" onMouseover="lightup('pic2')" onMouseout="turnoff('pic2')"> <IMG SRC="http://www.pageresource.com/images/story1.gif" name="pic2" width="100" height="25" border="0"></A>

Now you will have two changing images linking to different places!

 

Do this for as many image links as you wish.....it can add a nice impact to your page for those with newer browsers.

Well, that does it for now. Let's move on to the next section, JS Hover Buttons 2: Changing a Different Image. 

So, you want your script to change a different image when you place your mouse on the first one, or maybe when you place your mouse on a link. Check out the images below. Place your mouse over the top one, and watch the bottom image change!

 

We are going to see how to do that using the hover button script from the first rollover tutorial, but adding a few modifications. You will need to be familiar with the first hover button tutorial before you proceed.

Here is the script, read through it and see if you can catch the trick that changes a different image than the one the mouse goes over:

<SCRIPT language="JavaScript"><!--

if (document.images) { pic2on= new Image(100,25);

Page 38: Javascript Tutoriallll

pic2on.src="story2.gif"; pic2off= new Image(100,25); pic2off.src="story1.gif"; }

function lightup(imgName) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; } }

function turnoff(imgName) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; } }

//--></SCRIPT>

</HEAD>

<BODY>

<A HREF="newpage.html" onMouseover="lightup('pic2')" onMouseout="turnoff('pic2')"><IMG SRC="shoes1.gif" name="pic1" width="100" height="25" border="0"></A><P><IMG SRC="story1.gif" name="pic2" width="100" height="25" border="0"></BODY>

So, did you see the trick? Don't worry, if you didn't we'll get to it in no time. First, let's look at how the script gets started:

Detection and Preloading

First, like we did before, we check for the image object:

if (document.images) { .. }

Once the that has been checked, we preload the images we need for the mouseover. Notice that we only preloaded the images for the second picture. This is the one we want to change, while the first one stays the same:

if (document.images) {

Page 39: Javascript Tutoriallll

pic2on= new Image(100,25); pic2on.src="story2.gif"; pic2off= new Image(100,25); pic2off.src="story1.gif"; }

Now we are ready for the functions.

The Functions

Actually, the functions remained unchanged, except that we used an object detection again in place of browser detection.

function lightup(imgName) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; } }

function turnoff(imgName) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; } }

Everything else is the same, we just need to change one image on the mouseover. The trick to making it change a different image comes in the parameter we are going to send the function when we call it. So, on to the HTML code, where we will call the functions.

The HTML: Calling the Functions

Now, we get to the point where we call the functions with the onMouseover and onMouseout commands. We do this when the mouse is over the first image, which we will use as a link to "newpage.html". It could link to anything you want, or nothing at all- but you will need the link tag to call the onMouseover and onMouseout commands. Here is the HTML:

<A HREF="newpage.html" onMouseover="lightup('pic2')" onMouseout="turnoff('pic2')"><IMG SRC="shoes1.gif" name="pic1" width="100" height="25" border="0"></A><P><IMG SRC="story1.gif" name="pic2" width="100" height="25" border="0">

Now, notice that the first image is named "pic1", in the name="pic1" attribute of the image tag. The image we want to change is the one below it (the second image tag), which is named "pic2" using name="pic2"

Page 40: Javascript Tutoriallll

in the image tag. Now, look at the link tag that is used for the first image. When it uses the onMouseover command, look at the parameter to the function call:

onMouseover="lightup('pic2')"

Yes, it is telling the function to change 'pic2', which is the other image below it! So, the function performs the work on the second image, and leaves the first image as merely a link, a link that changes the second image while the mouse is over it. The onMouseout command does the same thing, just in reverse. It changes the second image back to normal.

What about a Plain Link?

To use a regular link to change the image, just remove the first image tag in the HTML, and replace it with text, like this:

<A HREF="newpage.html" onMouseover="lightup('pic2')" onMouseout="turnoff('pic2')">New Page</A><P><IMG SRC="story1.gif" name="pic2" width="100" height="25" border="0">

Now, you get something that looks like this:

New Page 

This script could be used to display a graphic with text while the mouse is on another image- the graphic could describe where the link will go when it is followed. You could also make some other nifty effects, try it out and see what you can come up with!

Well, that's it for now, let's go on to: JS Hover Buttons 3: Multiple Images. 

Well, how do you go about changing more than one image at a time? Maybe you want the image the mouse is over to changeand have another change at the same time. Here is an example below. Move your mouse over the top image, and both images change!

 

This comes from the same script we have been using in the previous rollover tutorials. You will need to be familiar with JS Hover Buttons and JS Hover Buttons 2 before you proceed.

Now, this script will also use Object Detection like we did in the previous section. This time, we want to change both images when the mouse is over the top one. Again, I'll start by giving you the complete script for this trick. See if you can catch the changes that make the script change more than one image at a time:

<BODY><SCRIPT language="JavaScript">

Page 41: Javascript Tutoriallll

<!--

if (document.images) { pic1on= new Image(100,25); pic1on.src="shoes2.gif"; pic2on= new Image(100,25); pic2on.src="story2.gif";

pic1off= new Image(100,25); pic1off.src="shoes1.gif"; pic2off= new Image(100,25); pic2off.src="story1.gif"; }

function lightup(imgName,imgName2) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; imgOn2=eval(imgName2 + "on.src"); document[imgName2].src= imgOn2; } }

function turnoff(imgName,imgName2) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; imgOff2=eval(imgName2 + "off.src"); document[imgName2].src= imgOff2; } }

//--></SCRIPT></HEAD>

<BODY><A HREF="newpage.html" onMouseover="lightup('pic1','pic2')" onMouseout="turnoff('pic1','pic2')"><IMG SRC="shoes1.gif" name="pic1" width="100" height="25" border="1"></A><BR><IMG SRC="story1.gif" name="pic2" width="100" height="25" border="1"></BODY>

Well, did you see what we did? Yes, the functions changed. Each function now takes two parameters. Also, when we call the functions from our HTML code, we call them with two parameters.

The Functions

Page 42: Javascript Tutoriallll

Let's take a look at the lightup() function:

function lightup(imgName,imgName2) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; imgOn2=eval(imgName2 + "on.src"); document[imgName2].src= imgOn2; } }

The function takes in two variables from the outside (parameters). It takes in imgName and imgName2. These will correspond to the names of the images, pic1 and pic2. So, the value of imgName is "pic1" and the value of imgName2 is "pic2". Now, you will see the code we used to change a single image before:

imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn;

Those two lines change our first image (pic1).

Now look at the next two lines. Yes, they are identical- except we changed the variable names by adding a 2 on the end of them. This way, the code works on imgName2, which is "pic2", the name of our second image. These lines are what changes the second image:

imgOn2=eval(imgName2 + "on.src"); document[imgName2].src= imgOn2;

Nice, isn't it? The turnoff() function does exactly the same thing in reverse. It switches the images back to normal.

The HTML

Now, we have to call the functions from our link tag around the first image. We use the onMouseover and onMouseout commands for the function calls:

<A HREF="newpage.html" onMouseover="lightup('pic1','pic2')" onMouseout="turnoff('pic1','pic2')"><IMG SRC="shoes1.gif" name="pic1" width="100" height="25" border="1"></A><BR><IMG SRC="story1.gif" name="pic2" width="100" height="25" border="1">

Let's look at the call from the onMouseover command:

onMouseover="lightup('pic1','pic2')"

Notice that it calls the function with two parameters. The first is the name of the top image, "pic1". The second parameter is the name of the bottom image, "pic2" (in the name="pic2" attribute). This allows the function to change both images while the mouse is over the top one. The onMouseout command calls the turnoff() function with the same parameters, so the images change back when the mouse goes away.

Page 43: Javascript Tutoriallll

Can I do 3 or More?

Yes, just add an extra two lines to both functions like we did above for each additional image, changing the variable names- by adding a 3, 4 and so on- to the end of the variable names. You will also need to add an extra parameter to both functions, and to both function calls in the HTML. So, if you use the script to change 3 images, you would change both of these functions like this:

function lightup(imgName,imgName2,imgName3) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; imgOn2=eval(imgName2 + "on.src"); document[imgName2].src= imgOn2; imgOn3=eval(imgName3 + "on.src"); document[imgName3].src= imgOn3; } }function turnoff(imgName,imgName2,imgName3) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; imgOff2=eval(imgName2 + "off.src"); document[imgName2].src= imgOff2; imgOff3=eval(imgName3 + "off.src"); document[imgName3].src= imgOff3; } }

Also, don't forget to preload the new images with the others at the beginning of the script. Just add the new image like you did for the others.

Then, you have to change the function calls, and add the extra image to your HTML code:

<A HREF="newpage.html" onMouseover="lightup('pic1','pic2','pic3')" onMouseout="turnoff('pic1','pic2','pic3')"><IMG SRC="shoes1.gif" name="pic1" width="100" height="25" border="1"></A><BR><IMG SRC="story1.gif" name="pic2" width="100" height="25" border="1"><BR><IMG SRC="another1.gif" name="pic3" width="100" height="25" border="1">

Well, try it with 50 images or so- maybe you can drive yourself insane looking for syntax errors through 50 images! Well..maybe not. See what you can come up with, and have fun with multiple rollovers!

Well, let's go on to yet another rollover idea in the next section: JS Rollovers 3. 

Now that we have changed images in all sorts of other ways, we are left with: "How to change one image to various other images when a viewer runs the mouse over a set of links or linked images". A long explanation, but the script for this is the shortest rollover script we have written yet. Of course, we are

Page 44: Javascript Tutoriallll

going to make a couple of adjustments that we didn't make in the earlier scripts in order to condense the code a bit.

First, let's look at an example of what I was tryng to say in that long quote at the beginning. A visual has to be better than that quote I wrote, right? Here it is, place your mouse over some of the links below and watch the image change accordingly:

Noise    Yellow    Big Face    Seeing Spots

This comes from the same script we have been using in the previous rollover tutorials. You should be familiar with JS Hover Buttons and JS Hover Buttons 2 as they help explain the basics about the preloading and such. This script will also useObject Detection like we did in the previous sections.

The HEAD Section Code

Now that we have the example, we need some code to see how this thing works. Let's start by looking at the code for the HEAD section of the page, here it is:

<SCRIPT language="JavaScript"><!-- if (document.images) { image_off= new Image(100,100); image_off.src="http://www.pageresource.com/images/scare.jpg";

image2= new Image(100,100); image2.src="http://www.pageresource.com/images/scare2.jpg"; image3= new Image(100,100); image3.src="http://www.pageresource.com/images/scare3.jpg"; image4= new Image(100,100); image4.src="http://www.pageresource.com/images/scare4.jpg"; image5= new Image(100,100); image5.src="http://www.pageresource.com/images/scare5.jpg"; }

function change1(picName,imgName) { if (document.images) { imgOn=eval(imgName + ".src"); document[picName].src= imgOn; } }//--></SCRIPT>

Page 45: Javascript Tutoriallll

Pretty short in comparison to our previous rollover scripts, isn't it? The preloading is basically the same. However, rather than adding "on.src" at the end of the image location definitions, we simply add .src to it. This is one are where we shorten the coding a bit. Since the image is "on" anytime a link is hovered, the "on" bit would not serve as a helpful hint here. We do have one named image_off, since this would be the default image and might help. The other images are just given a different number like "image2", "image3" and so on. These changes will make more sense as we look at the function.

The function begins by taking two parameters (yes, parameters agian!). The first is the name of the image in your image tag, where you write your name="name" attribute (In this script, the name is pic1, see the IMG tag in the BODY code below). The second parameter is the name of the image object that will replace the default (off) image when the mouse moves over the link.

After that, we detect the image object. Then, we use the parameters to change the default image.

imgOn=eval(imgName + ".src");

This takes the image name and adds the .src to it so the script finds the location of the replacement image. It assigns that url to the imgOn variable.

document[picName].src= imgOn;

This actually changes the image. You'll see the picName variable is used, so that the image name sent into that variable (pic1 for this script) is changed to the replacement image.

The turnoff() function used on the onMouseout event in the previous scripts was repetitive. It did the same thing as the lightup function, but on the onMouseout event. It was used for clarification, but now we can just use this single change1() function for the onMouseover and onMouseout events to condense the code further. This helped shorten the code quite a bit here.

The BODY Section Code

This is where the functions are called and the parameters are set. Here is the code, (preformatted):

<P><A HREF="url" onMouseover="change1('pic1','image2')" onMouseout="change1('pic1','image_off')">Noise</A>&nbsp;&nbsp;<A HREF="url" onMouseover="change1('pic1','image3')" onMouseout="change1('pic1','image_off')">Yellow</A>&nbsp;&nbsp;<A HREF="url" onMouseover="change1('pic1','image4')" onMouseout="change1('pic1','image_off')">Big Face</A>&nbsp;&nbsp;<A HREF="url" onMouseover="change1('pic1','image5')" onMouseout="change1('pic1','image_off')">Seeing Spots</A><P><IMG SRC="http://www.pageresource.com/images/scare.jpg" name="pic1" width="100" height="100" border="0">

Just change the urls and text to your own choices. Then, you'll see that all the onMouseout calls are the same. You will want your onMouseout calls to be the same too (not necessarily exactly like this one, but they should all match each other). The onMouseout command calls the default image object you defined while preloading. Ours was named "image_off".

Page 46: Javascript Tutoriallll

The calls made onMouseover only change the second parameter. It is changed to one of the replacement image objects you defined while preloading. Just choose the one that fits with your link.

Finally, be sure the name="name" attribute in the IMG tag matches the first parameter you send to the function in each case. Ours was pic1, but you may choose another name-- just be sure to change the function calls to match it.

You'll notice that the pic1 parameter didn't change in any of the function calls, so you may wonder why we should bother with the parameter and just use pic1 in the function itself. The reason is so you could use this function for more than one image/link set on the page. Just be sure to give the other image(s) a new name in the IMG tag in the name="name" attribute. For instance, the second one could have name="pic2". You could then call the function by replacing all the pic1 parameters with pic2, and now the first parameter has a use. Then again, the use of it just depends on how many times you want to use the effect on a single page.

Well, that does it for now, let's get a better explanation on object detection in the next section: JS Object Detection.

Do you remember the browser detection script we worked on a while back? Then you probably remember how much trouble it was to detect a specific browser type before we could run certain scripts. Here was how we had to do it:

browserName=navigator.appName; browserVer=parseInt(navigator.appVersion); if ((browserName=="Netscape" && browserVer>=3) || (browserName=="Microsoft Internet Explorer" && browserVer>=4)) version="n3"; else version="n2";

That is a lot of code to run through, and it can be much worse when you create a script that has a lot of browser differences. Well, instead of checking for the browser, we could have checked for the javascript object that we needed for the script to work. Since we know that a hover button script needs the document.images object to work, we could shorten the above code to say:

if (document.images) { ...code...}

In fact, this object just so happens to exist in the browsers we checked for, and not in the browsers that were excluded. So, using this object detection code, we are checking for Netscape 3 or higher, and MS Internet Explorer 4 or higher! And as a bonus, if any other browser happens to recognize the document.images object, the script will run for them too! (Opera perhaps?)

You can also use a couple of the new objects to check for version 4 browsers. If you are looking only for NS4, check for the document.layers object:

if (document.layers) { ...code...}

If you want only IE4, check for the document.all object:

if (document.all) { ...code...}

Page 47: Javascript Tutoriallll

Of course, if you just want it to work for either version 4 browser, check to see if the browser has one object or the other:

if (document.all || document.layers) { ...code...}

For IE 5:

if (document.getElementByID && document.all){ ...code...}

For NS 6:

if (document.getElementByID && !document.all){ ...code...}

For both IE5 and NS6 (or better):

if (document.getElementByID){ ...code...}

You can find some more uses for this as you are coding, so that you can avoid those pesky javascript errors in older browsers. While you are at it, it will probably keep away those errors with the newer browsers as well.

Well, that does it for now, try out the next section on JavaScript and Frames. 

JavaScript and Frames. Frames and JavaScript. Sounds like a mess doesn't it? Well, it does make things a bit more complicated. Let's see if we can figure out how to get those frames to work with our scripts.

The first thing you will want to know is "How in the land of JavaScript do I access javascript variables and other things in one frame from another frame? The answer is to use a trick like this:

parent.framename.attributes_to_change

Replacing framename with the name you gave the frame in your frameset, ie:

<FRAME src="jex14.htm" name="right_frame">

In this case, you would access something in that frame with:

parent.right_frame.attributes_to_change

Let's start by changing the value of a text box in a frame on the right from a frame on the left side. First, set up a little frameset. This will require 3 separate html pages. Your frameset, and the html for your 2 frames. Let's begin with the frameset:

<HTML><HEAD><TITLE>Frames Values</TITLE></HEAD><FRAMESET cols="20%,80%">

Page 48: Javascript Tutoriallll

<FRAME SRC="jex13.htm" name="left_frame"><FRAME SRC="jex14.htm" name="right_frame"></FRAMESET></HTML>

The two pages I will use inside the frameset are "jex13.htm" and "jex14.htm". The left side (jex13.htm) will have this html code:

<HTML><HEAD><TITLE>JavaScript Example 13</TITLE></HEAD><BODY><FORM><INPUT type="button" value="What is cool?" onClick="parent.right_frame.document.form1.text1.value='Me!'"></FORM></BODY></HTML>

This is where we use our new command, inside the onClick=" " command:

onClick="parent.right_frame.document.form1.text1.value='Me!'"

As you can see, we access the right frame with the "parent.right_frame." and then we add what we want to change onto the end. Since we want to change something inside the document object, we have to use "parent.right_frame.document.". If you leave out the "document" the browser defaults to using the "window" object, which we will use later on. But for now, we want the "document" object. Now, to access the form, we tack on the name of the form, "parent.right_frame.document.form1.". Then, we access the textbox by adding the name of the textbox onto it: "parent.right_frame.document.form1.text1.". Finally, we can access the value attribute of the textbox by placing value at the end, and assigning it a value with the eqaul sign:

"parent.right_frame.document.form1.text1.value='Me!'"

So, we now have a button that will change a textbox in the right_frame. The html code for the right frame (jex14.htm) is simply a form with an empty textbox:

<HTML><HEAD><TITLE>JavaScript Example 14</TITLE></HEAD><BODY><FORM name="form1"><INPUT type="text" name="text1" size="25" value=""></FORM></BODY></HTML>

Now, you can see an exaple of our....well...master frames script:

Sample

Page 49: Javascript Tutoriallll

Well, if you liked that trick, let's see an even better one. Let's move on to: Changing 2 Frames at Once with JavaScript. 

Previous

By: John Pollock

Next

You want to change more than one frame at a time? OK, well here is how to do make the trick work for you!

The first thing you will need is a frameset to get you started. Again, I will use a frameset with two frames. Here is the code for the frameset page:

<HTML><HEAD><TITLE>Frames Example 5</TITLE></HEAD><FRAMESET cols="20%,80%"><FRAME SRC="page1.htm" name="left_frame"><FRAME SRC="page2.htm" name="right_frame"></FRAMESET></HTML>

Be sure you give each frame a name using the name=" " attribute. I named the frames above "left_frame" and "right_frame".

Now, create html files for each frame you will need to use. Since I have two frames, and want to change both frames at once, I need 4 html files. I called mine "page1.htm", "page2.htm", "page3.htm", and "page4.htm".

Now, since I am using the left frame for my navigation, that is where I am going to put the link to change the two frames. The html page for the right frame does not need to be modified at all, unless you just want to....

Edit the Left Frame HTMLNow, to make this work, we need to edit the html page that makes the left frame. In this case, the left frame is "page1.htm". So this is the file we need to work on. Here is what we need to have in the html code to get the link to change multiple frames:

<HTML><HEAD><TITLE>FRAME 10</TITLE><SCRIPT language="JavaScript"><!--hidefunction change2(){parent.left_frame.location="page3.htm";parent.right_frame.location="page4.htm";}//--></SCRIPT>

Page 50: Javascript Tutoriallll

</HEAD>

<BODY bgcolor="#FFFFFF" text="#000000"><CENTER>Click the link below to change both frames.<BR><A HREF="javascript:change2()">Change 2 Frames</A></CENTER></BODY></HTML>

The JavaScript FunctionDon't worry, it isn't as bad as it seems. The important lines are:

parent.left_frame.location="page3.htm"; parent.right_frame.location="page4.htm";

That is where you tell the browser what html pages you want to change both frames to, and where you use the frame names we gave our frames earlier. In general, it would look like this:

parent.your_frame_name.location="url"; parent.your_other_frame_name.location="url";

Replace your_frame_name with the name of your frame from earlier. Replace url with the web address of the page you want to change to. Mine was named "left_frame", and I wanted to change the page to "page3.htm", so I got the line:

parent.left_frame.location="page3.htm";

Do the same for the second frame. My other frame was named "right_frame" and I wanted to change to "page4.htm":

parent.right_frame.location="page4.htm";

That's the only part of the script you really have to edit. If you used the same names and pages I did, you didn't need to edit at all. As far as the url goes, you can also use a full url if the page you want to link to is not in your directory. You could have something like this:

parent.left_frame.location="http://www.someplace.com/somepage.htm";

What's With the Link Tag?<A HREF="javascript:change2()">Change 2 Frames</A>

You probably also noticed that the link tag does not link to a normal url. This is because it is calling our javascript function, which is what we are using to change the urls. This is why we can change two at the same time. If you want more information on how the javascript link works, see the JavaScript Link Tutorial..

Give it a TryTo see the code in action, click the link below for a sample page:

Example Page

Page 51: Javascript Tutoriallll

In the example, you probably saw that I had a link to change the frames back again. If you want to add a link like that, you will need to edit the second left frame's html code. In my example, it would be "page3.htm" that you would need to edit. You can add the same script and code, but change the urls in the javascrpt function to lead back to your first two frames. I wanted to go back to "page1.htm" and "page2.htm". My example code for the url change looked like this:

parent.left_frame.location="page1.htm"; parent.right_frame.location="page2.htm";

Now, give it a try yourself. If you are using frames, this may be a handy trick for you sometime.

Let's go on to: JavaScript and Forms. 

You can do many things with javascript using your forms. Great, you say, but where does one figure out how to access those form elements with javascript? Well, if I were in a good mood, I might tell you! .....Oh, all right, I'll tell you anyway...........

You can access various parts of a form by naming them. In turn, you must give the form a name, because it will be part of what you need to get to what you want. Take a look at the following form code:

<FORM name="coolform"> <INPUT type="text" name="cooltext" value="I am Cool!!!" size="20"> </FORM>

This code creates a little input box for text. The value="I am Cool!!!" attribute gave this box an initial value, which can be changed if the viewer types something else.....OR..... if you were to change it with javascript! Here is what the box looks like:

You can go up there and type something else if you like......just keep it clean, OK? :-)

Now, recall from the code above that we gave this form and the box names. This is how we will get to them with javascript. Now, the input box is part of the form, and the form is part of the document. If you remember the document.location object from a previous section, you know we can access parts of the document and change them. (document.location allowed us to change the url and go to a different page). So, to access the form, we would use:

document.coolform

Remember, the name of our form is "coolform" from the name="coolform" attribute inside the form tag. Now, to access the text box, you would add on the name of the text box:

document.coolform.cooltext

Again, the name of the text box was used. We had named it "cooltext".

Now, we can access the value of the text box, which is what is in the value=" " attribute. So, if we wanted to get to the value of the box....the text "I'm Cool!!!", we would add the word "value" to the end of the list:

document.coolform.cooltext.value

I am Cool!!!

Page 52: Javascript Tutoriallll

Notice that each time we add something to the list, it is separated from the others by a dot. This is because we are using "objects" to get what we need. The document, the form, and the text box are all objects in the browser. The addition of the "value" at the end lets us access the value of the text box object. The text box object was part of the form object, and the form object......yes, it is part of the document object!

Now that we can get to the value of the text box, we should be able to do something with it, right?.... Getting the idea? Yes, let's try to change the text in the box! One way to do this is to let the viewer click a button and change the text when the button is clicked. For the above form, we can simply add a button at the end, and use the old "onClick" function to perform a javascript. Here is the sample code:

<FORM name="coolform1"> <INPUT type="text" name="cooltext" value="I am Cool!!!" size="20"> &nbsp;&nbsp; <INPUT type="button" name="change" value="Click to see new text!" onClick="document.coolform1.cooltext.value='You are cool too!!'"> </FORM>

Notice that I gave this form a new name (coolform1). If you have more than one form on the same page, be sure they all have different names. Otherwise when you try to access the form, the browser won't know which form you want to go to, because they have the same name! So....... This gives you the following box and button. If you are feeling rather cool today, click on the button to change the text in the text box....

    

You can also change the text on a button that is clicked in the same way:

<FORM name="coolform2"> <INPUT type="button" name="coolbutton" value="Click Here and see what I have to say!" onClick="document.coolform2.coolbutton.value='Who told you to Click ME?'"> </FORM>

Be sure to make the initial set of text in the value=" " attribute longer than the text you want to change it to. The button will need the room to write your new text! Try out the button below:

Knowing this will come in handy in the next section, where you will see how to access a select box and learn the next trick:JavaScript Drop Boxes. 

So, you have been thinking about adding a drop box for people to navigate your page with. One problem.....how is it done? Below is a sample navigation drop box. Choose a page, and click the "Go!" button. You will be taken to the page you asked for. (Both are kind of boring by the way). Give it a try below:

    

For this drop box to do this, we must use a javascript that will access the Select Box and then go to the new destination.

In the last section, we learned how to access the value attributes of a text box and a button. We can access the Select Box in the same way. Below is the code used for the drop down box:

I am Cool!!!

Page 1

Page 53: Javascript Tutoriallll

<FORM name="guideform"> <SELECT name="guidelinks"> <OPTION SELECTED value="jex6.htm">Page 1 <OPTION value="jex7.htm">My Cool Page </SELECT> &nbsp;&nbsp; <INPUT type="button" name="go" value="Go!" onClick="window.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value"></FORM>

Notice that we gave the form and the select box a name. These are used later to access the value attribute of the Select box. (If you scrolled out to read all of that, you saw it got pretty messy there). We also gave the value=" " attribute to each OPTION tag. You will notice the values are urls. The url is where we want the browser to go when the user selects that option. So, for the first option, <OPTION SELECTED value="jex6.htm">Page1, we want the browser to go to "jex6.htm" when the user chooses the option "Page 1". You can change this to any url you wish.

The tricky part here is accessing the Select Box in order for a viewer to navigate the site. You see that we can get to the select box itself easily using the name attributes:

document.guideform.guidelinks

But this doen't give us access to the options inside the select box. It only gives us access to the box itself. To access the options, we must add on the options property:

document.guideform.guidelinks.options

Now that we can get to the options, we can access each option individually using some special notation. (The options create a numbered array, if you are familiar with arrays). You don't have to know about arrays to get the idea. Just remember that the first option listed is option 0, written as options[0] . You see the square brackets? That is what tells us an array is being used. The second option in the list will be options[1]. Just remember that arrays will start with 0 instead of 1, so you will have to use options[0] to access the first option directly.

Well, now we can get to the value attribute of the first option like this:

document.guideform.guidelinks.options[0].value

The value would be "jex6.htm". This is nice, but if you want to be able to use the selected option each time so the viewer can go to the url of their chosen option, the script will need to know which option the user has selected. Since we can't just guess they will choose options[0] or options[1], we will have to find a way to access the correct one each time the user makes a new selection. This is done by using a new property, selectedIndex.

The selectedIndex property tells the script the number of the option the user selected, so that it will not always be the same. So the script will not always be stuck on options[0] or options[1], it will get the one that is selected each time.

This gives us a new problem....when we access the value of an option, we were just allowing it to be one option or another....we didn't allow it to change if another option was selected:

document.guideform.guidelinks.options[0].value

Page 54: Javascript Tutoriallll

This would give us "jex6.htm" every time.....and we want the value to be changed when the user selects another option. So...we have to alter the value inside the array part of this already long string of words. The selectedIndex property will give us a number....the number of the option the user has selected. So, we will have to put the selectedIndex property inside the array brackets so that we end up with a number inside the brackets.....But this number changes each time a new option is selected. To access the value of the selectedIndex property, we again have to go through the name of the form and the name of the select box:

document.guideform.guidelinks.selectedIndex

Now, to put it all together, we put the value of the selectedIndex inside the brackets of the full value of the option:

document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value

What will happen is that you will get one of the following, depeneding on which option was selected:

document.guideform.guidelinks.options[0].value OR document.guideform.guidelinks.options[1].value

Of course, you can add as many options as you wish, they will just be options[2], options[3], and so on. The beauty of the selectedIndex property is that you won't have to deal with the numbers, you will just be able to add options and let the javascript take care of the rest.

You will also notice way back in the script above that we called the javascript commands with the onClick=" " command in the button tag. The button triggers the change of urls by changing the value of the window.location:

<INPUT type="button" name="go" value="Go!" onClick="window.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value">

That is where everything is put together to make the drop down box work. The browser goes to the url that is the value of the option the viewer selected. A little messy, but that is the way javascript is sometimes.

Well, that does it for now, try out the next section on Drop Boxes- No Button. 

Now that you have seen the javascript drop box with the button, you may want to know how to make a drop box change pages without requiring the viewer to click a button. Instead, you want it to change pages as soon as a choice is selected.

Well, the code for this is actually shorter than the drop box with the button. All that is new here is that you will need to learn the onChange attribute. The onChange attribute is another way of calling javascript when something happens. It is coded in much the same way as onClick or onMouseover. The difference is that this attribute is used in form elements, select boxes. The onChange attribute will perform javascript statements when something inside your form element is changed. In this case we will be changing a select box. Here is a quick example of the onChange attribute. You can send someone a message when they choose something:

<FORM> <SELECT name="sport" onChange="alert('I\'m glad YOU can make choices!')"> 

Page 55: Javascript Tutoriallll

<OPTION SELECTED>--Choose a Sport-- <OPTION>Football <OPTION>Basketball </SELECT> </FORM>

You can try it out below. It isn't very useful, but it works....

Now, we can get to the useful application. You can use the onChange attribute to do the same thing that we did with the onClick in the button in the last section. In other words, the onChange attribute will now

load the new url when someone makes a selection. A new sample drop box is below. Give it a try:

In the last section, we learned how to access the value of the select box and change the page the person is vieweing. If you haven't seen this yet, go back to the first drop box tutorial.

Other than removing the button and moving the window.location code to the onChange attribute in the Select tag, this is the same script:

<FORM name="guideform"> <SELECT name="guidelinks" onChange="window.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value"><OPTION SELECTED value="jdrop2.htm">--Choose--<OPTION value="jex15.htm">Page 1 <OPTION value="jex16.htm">My Cool Page </SELECT> </FORM>

Notice that the default option selected just tells you to choose something. It won't lead anywhere unless someone tries to change back to it. I used the url of the page it was on for the value of it, so the browser will stay on the same page if it gets selected later. This isn't likely to happen though. I couldn't go back and change back to the default option from another option when I tried. The browsers just went back and loaded the page with the default selection already selected again.

Well, there is your drop box with no button. Go change the urls and have some fun with it!

Well, that does it for now, try out the next section on Drop Boxes and Frames. 

Before moving through this, you may want to read through one or more of the tutorials leading up to this one. You should be familiar with JavaScript Drop Boxes, and you may want to read aboutJavaScript and Frames.

Making a javascript drop down box work with frames isn't as bad as it seems. The question is, where do you put in the target information? Well, you can't do this directly, because the script just won't understand something like this:

window.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value target="right"

If you have read the frames with javascript sections, you may have an idea about how to get your target into this code. What we need to do is make an adjustment on the left of the "=" sign. When you change

--Choose a Sport--

--Choose--

Page 56: Javascript Tutoriallll

the window.location value, the new page opens in the current window, whether it is in a frame or not. But with frames, you want the page chosen from a drop box to open in another frame, not in your navigation frame.

The trick is to change window.location to this:

parent.framename.location

What you do is change the word framename above with the name of your target frame, or what you would normally write inside the target=" " attribute.

So, suppose you had a frameset like the one below, using the left frame for navigation and the right frame for content:

<HTML><HEAD><TITLE>Frames Example 1</TITLE></HEAD><FRAMESET cols="20%,80%"><FRAME SRC="jex18.htm" name="left_frame"><FRAME SRC="jex19.htm" name="right_frame"><NOFRAMES>Sorry, you can't see this page..</NOFRAMES></FRAMESET></HTML>

Now, since we want the drop box in the left frame, that is the page we need to modify. Above, the left frame is "jex18.htm", and we want to open our drop box links in the right frame, "jex19.htm". Notice how the FRAME tag uses the name=" " attribute. We will need this when we write the code for the drop box.

Now, edit your left frame HTML by adding the dropbox. The thing we need to concentrate on is getting the target frame correct. With our frameset, the right frame is named "right_frame". This is what we use to change our command line when the go button is clicked:

parent.right_frame.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value

Now, everything your viewers choose from the drop box will open in the right frame. The complete drop box code is below:

<FORM name="guideform"> <SELECT name="guidelinks"> <OPTION SELECTED value="jex20.htm">Page 1 <OPTION value="jex21.htm">Cool Page </SELECT> &nbsp;<INPUT type="button" name="go" value="Go!" onClick="parent.right_frame.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value"></FORM>

If you want to see this in action, check out the example below by clicking the View Example link:

Page 57: Javascript Tutoriallll

View Example

What if I'm using the no-button Drop Box?

You do the same thing with the code, changing only the information to the left of the "=" sign. The code for one of these is below:<FORM name="guideform"> <SELECT name="guidelinks" onChange="parent.right_frame.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value"> <OPTION SELECTED value="jex20.htm">Page 1 <OPTION value="jex21.htm">Cool Page </SELECT> </FORM>

So, now you have the drop box working with your frames, rather than against them- or maybe that should be the other way around?

Well, that does it for now, try out the next section on More JavaScript Buttons. 

If your browser is a version 4 or better, click on the image below. It works in the same way as a form button, but we can use the mouseover effect and customize the color. Give it a try:

Now how in the world is that done? Well, version 4 browsers allow us to use a few more mouse events. This button uses the onMouseover and onMouseout, and two new ones: onMouseDown and onMouseUp. These work in much the same way, they are just call when a viewer clicks or lets go of the mouse button:

onMouseDown    The viewer clicked the mouse button.

onMouseUp    The viewer let go of the mouse button.

How is this different than onClick? With these events, we are able to separate the click into its two parts: The button going down, and the button going back up. In this way, we are able to change the image to act like a form button. When you press the mouse button down, you get the "down button" image. When you let go, you get the "up button" image. Let's look at the HTML first this time (the reverse of my normal routine!). You will see that we can call a function on each event:

<A HREF="javascript:void(0)" onMouseover="lightup('pic1')" onMouseout="turnoff('pic1')" onMouseDown="clickdown('pic1')" onMouseUp="lightup('pic1')"> <IMG SRC="http://www.pageresource.com/images/upbutlav.gif" name="pic1" width="62" height="28" border="0"> </A>

Also, you'll notice that I made the image do nothing when clicked. I used a javascript link, but a special one. I linked to the void() function, which does nothing when you send it zero! So you could simply link to nothing like this:

<A HREF="javascript:void(0)">Click Here!</A>

The link would do nothing, but sometimes it comes in handy.

Page 58: Javascript Tutoriallll

Now, back to the script. To get this image to do all of these things, we have to have the functions. So, here is the script for your HEAD tags:

<HEAD> <SCRIPT language="JavaScript"> <!-- if (document.images) { pic1on= new Image(62,28); pic1on.src="http://www.pageresource.com/images/upbutblue.gif"; pic1off= new Image(62,28); pic1off.src="http://www.pageresource.com/images/upbutlav.gif"; pic1down=new Image(62,28); pic1down.src="http://www.pageresource.com/images/dbutblue.gif"; }

function lightup(imgName) { if (document.images) { imgOn=eval(imgName + "on.src"); document[imgName].src= imgOn; } }

function turnoff(imgName) { if (document.images) { imgOff=eval(imgName + "off.src"); document[imgName].src= imgOff; } }

function clickdown(imgName) { if (document.images) { imgDown=eval(imgName + "down.src"); document[imgName].src=imgDown; } } //--> </SCRIPT> </HEAD>

You'll notice this is the same script I used for the hover buttons, but with a couple of modifications. I updated the code to use object detection, and I added a new function called clickdown() to be used on the onMouseDown event.

Page 59: Javascript Tutoriallll

The object detection simply checks to see if the browser can support the script. Here, we can check for the document.images object. This is an object that allows for javascript to access the images in a document. If it exists, the browser moves on with the script. If not, it ignores what follows the check.

Also, when you use the script be sure you have the third image. The "down button" image will be needed for our clickdown() function. So, this script uses three images:

 upbutlav.gif This is the image used when nothing is going on.

 upbutblue.gif This is the image used when the viewer moves the mouse over the image, and when the mouse button is let go (onMouseUp).

 dbutblue.gif This is the image used when the viewer presses the mouse button (onMOuseDown).

The new function does the same thing the old ones did, it changes the image. If we look at the HTML code again, you will see that we call our new clickdown() function with the onMOuseDown event. This makes the image change when the viewer presses the mouse button, so we get the "down button". As for the onMouseUp, we reuse the lightup() function, since this holds the image for the "up button".

Now, in your HTML, you can use a live link instead of the void(0) link:

<A HREF="http://www.pageresource.com/html/frame1.htm" onMouseover="lightup('pic1')" onMouseout="turnoff('pic1')" onMouseDown="clickdown('pic1')" onMouseUp="lightup('pic1')"> <IMG SRC="http://www.pageresource.com/images/upbutlav.gif" name="pic1" width="62" height="28" border="0"> </A>

Now, you would get a live button, like this one:

Well, that does it for this section, lets go on to: External JavaScripts. 

External Scripts Have you been looking for a way to use one page of javascript code on multiple pages, without needing to paste the code into page after page? Well, this is where an external javascript can help! You can call functions from an external javascript on any page that you put the special <SCRIPT></SCRIPT> tags on.

So, what do these special tags look like? They look like a plain script tag, but they use an extra attribute: The SRC="http://someplace.com/script_name.js" attribute.

Here is an example of one of these tags:

Page 60: Javascript Tutoriallll

<SCRIPT language="JavaScript" SRC="http://www.pageresource.com/jscript/jxt1.js"></SCRIPT>

The SRC attribute names a source for the javascript to be used. The script must be saved with the extension .js as a plain text file.

So, let's give it a try. Open a new document in your text editor, and write the following code into it:

function a_message() { alert('I came from an external script! Ha, Ha, Ha!!!!'); }

Now, save the file as "jxt1.js".

You can now use this script on any page you place the special script tags on. Place the script tags inside your <HEAD></HEAD> tags. Be sure the SRC attribute points to your .js file. If you are working in one directory, just use the tag this way:

<SCRIPT language="JavaScript" SRC="jxt1.js"></SCRIPT>

If not, try an absolute url. Be sure to change this to your domain and the correct directory:

<SCRIPT language="JavaScript" SRC="http://someplace.com/jxt1.js"></SCRIPT>

Now, you can call your message function from the page that you placed the tags on. I will use a link as an example:

<A HREF="javascript:a_message()">Click for a message..</A>

I used the same script for this example, clicking on the link will bring up our message from the external script. (If you are not familiar with this kind of link tag, see the JS link tutorial for details.

Click for a message..

This script is not very useful, it will just give you one alert message to use on every page (Yuck!). However, it shows you how to call a function from an external script (just like a normal function). I'm sure you can think of some better scripts to use with this. (Actually, I can too, but I'm too lazy to type out a long script here...).

This is a handy way to use one script on multiple pages. By adding the script tags to each page you need the script on, you can reuse a script over and over without typing the entire script on every page. Now, get out there and find some more useful scripts to use for your own external javascripts!

Well, that does it for now. Let's go on to The Date Object: JS Clock. 

Now, you would like to have a clock for your web page- but how do you go about coding such a clock with JavaScript? Using the date object and some of its methods, you can create your own javascript clock customized to your needs. Our script here will create a fairly simple clock, but we will also discuss some of the other methods of the date object you may wish to use to create and customize your own clock.

Page 61: Javascript Tutoriallll

To begin, we must discuss the javascript date object. This works a bit differently than the pre-defined functions we have used in past scripts. To use the method functions of the date object, we must create what is called an instance of the date object. Think of an instance of the date object as a variable or placeholder that allows us access to the member functions of the date object. Why think of it as a variable? Well, to create an instance of the date object, you define it as a new variable- but with a lttle twist:

var thetime=new Date();

As you can see, we are not assigning the new variable a direct value. Instead, the code above defines the variable as a new instance of the date object. This means we can use this variable in order to access the method functions of the date object. What are the method functions? Well, here a list of some of them:

Method Function

What the Function Does

getHours() Returns the current number of hours into the day: (0-23)

getMinutes() Returns the current number of minutes into the hour: (0-59)

getSeconds()Returns the current number of seconds into the minute: (0-59)

getDay() Returns the number of days into the week: (0-6)

getMonth() Returns the number of months into the year: (0-11)

getYear() Returns the number of years into the century: (0-99)

These are not all of the method functions, but they are enough to create a decent clock. Our example clock for this tutorial will only use the first three, but the rest my be useful to you to customize your clock.

Now, suppose we want to get the number of hours into the day. We could do this by defining a variable and giving it the value of the getHours() method function. However, the following line will give you an error:

var nhours=getHours();

Why? Well, remember that the getHours() function is a method function of the date object. In order to get that value for our variable, we have to use our instance of the date object we created earlier:

var thetime=new Date(); var nhours=thetime.getHours();

This is part of object-oriented programming. Once we have created an object, we are able to access its member functions with what is called "the dot operator". By placing the dot between our object name (thetime) and its member function, we are able to execute the member function. In this case, the function simply returns a value (the number of hours into the day). We are using this value as the value of our new variable, nhours.

We have used the dot operator in the past, when we used the document.write() function. The write() function is a member function of the document object, and the function writes text to the screen.

Page 62: Javascript Tutoriallll

An advantage of using objects is that objects can hold multiple values, where variables can only keep one value at a time. An object can also use any member functions it may have, like we did above. So, our date object named thetime can use all of the member functions. Now we can start getting the rest of the values for our clock. Let's get the hours, minutes, and seconds:

var thetime=new Date(); var nhours=thetime.getHours(); var nmins=thetime.getMinutes(); var nsecn=thetime.getSeconds(); 

See how we were able to use our object named thetime to grab three different values? It's almost fun, then again...yes, a bit more complicated than having a pre-defined object to use.

With these values and a bit of extra coding, we can create a clock like the one below:

Current Time: 

Not bad, but now we must get into the extra coding we need to get the clock running smoothly. Remember, thetime.getHours() returns the number of hours into the day. This value is a number between 0 and 23. What can we do if we do not want a 24 hour clock, if we don't want 11:24 P.M. to be 23:24? To get around that, we need some code that will change any number over 12 back to 1,2,3,4, and so on. We

can do this by subtracting 12 from our variable nhours when it has a value greater than 12:

if (nhours>=13) nhours-=12;

nhours-=12; is shorthand for: nhours=nhours-12;

Also, if the hour is 0, we know that is 12 A.M., so we need to make the zero into a 12. if (nhours==0) nhours=12;

Now, when the number of hours is 14, the script changes it to 14-12=2. Just what we needed.

We don't have the same problem for the minutes and seconds, but they present a problem of their own. Suppose the number of minutes into the hour is 32. This value is fine, the script will display a 32. However, what if the value is 2? The script would display something like this:

11:2

What? Yes, we need a way to get a zero in there so the clock is readable. We want it to say 11:02. So now we need something to add in a zero before the 2 if the number of minutes (nmins) is less than 10. Let's try this:

if (nmins<10) nmins="0"+nmins;

This code will add in the character 0 in front of the 2 if the number of minutes is less than ten. Another little problem out of the way, but we will also need to do this for the seconds:

if (nsecn<10) nsecn="0"+nsecn; 

Page 63: Javascript Tutoriallll

if (nmins<10) nmins="0"+nmins;

Had enough? Me too, but this clock still has another value we need to get. The clock displays A.M. or P.M. for morning and evening hours. This isn't to terrible. We can define another variable, let's call it AorP. We need the value to be "P.M." if the hour is greater than 12, and "A.M." otherwise. Here we go:

if (nhours>=12) AorP="P.M."; else AorP="A.M.";

One problem though. You need to place this section of code before our code that changes the clock to a twelve hour system. Otherwise, the hours will never get past 12, and it will always read A.M. Why? This is because when we change the clock to the twelve hour system, we change the value of nhours so that it is 0-12 in all cases. So, we must get our AorP value before we change the time system.

Now, I'll give you the code for the script:

<HEAD><SCRIPT language="JavaScript"><!--function startclock(){var thetime=new Date();

var nhours=thetime.getHours();var nmins=thetime.getMinutes();var nsecn=thetime.getSeconds();var AorP=" ";

if (nhours>=12) AorP="P.M.";else AorP="A.M.";

if (nhours>=13) nhours-=12;

if (nhours==0) nhours=12;

if (nsecn<10) nsecn="0"+nsecn;

if (nmins<10) nmins="0"+nmins;

document.clockform.clockspot.value=nhours+":"+nmins+":"+nsecn+" "+AorP;

setTimeout('startclock()',1000);

}

//-->

Page 64: Javascript Tutoriallll

</SCRIPT></HEAD><BODY onLoad="startclock()"><FORM name="clockform">Current Time: <INPUT TYPE="text" name="clockspot" size="15"></FORM></BODY>

You may have noticed we are accessing a form value and changing it in this line:

document.clockform.clockspot.value=nhours+":"+nmins+":"+nsecn+" "+AorP;

So, you now know we need a form in the body of the document. Here is the one that goes with the script:

<FORM name="clockform">Current Time: <INPUT TYPE="text" name="clockspot" size="15"></FORM>

Also, you can see that we use the setTimeout() function to run our startclock() function again after one second. In this way, the clock will refresh every second so that you get a constantly running clock with the seconds ticking away.

Of course, how do we get the thing started to begin with? The browser won't just run the startclock() function on its own. It needs some kind of event to happen. Well, how about when the page loads? Excellent choice, let's use the onLoad event. The onLoad command is used as an attribute in the body tag, much like defining a text color:

<BODY text="lime">

I'm not sure I could handle that text color for long, but now we can see how the onLoad command will be put to work:

<BODY onLoad="startclock()">

Nice, isn't it? The command works like the other event handlers, we are able to use it to call our javascript function. This is what gets the clock ticking.

Now, you can go make use of this clock if you need one. Otherwise, you have gotten a rather unorthodox introduction to objects and object-oriented programming. Well, maybe I'll add a more orthodox tutorial on the subject sometime, if I can stop saying the word orthodox. You know, I think the last half of this paragraph has been extremely unorthodox. Oops, I think I had better get going now..

Well, that does it for now, lets go to the next section: JS Clock 2.

Now, maybe you want your clock to include the day of the week and the date as well. This clock will iclude these features. Also, we will start the clock by calling the function inside the body section, so that the entire page does not have to load before the clock starts. Let's take a look at what the new clock will look like:

Current Time: 

Page 65: Javascript Tutoriallll

Yes, more information. This requires a few more things in the script to make it work the way we want it to. Be sure you have read the first clock tutorial before you proceed. It will cover some things you will want to

know before going through this section.

Now, let's take a look at the script. You will notice we called more member functions of the date object to get the extra information. See what other differences you can find before we get to the details. Here is the script:

<HEAD><SCRIPT language="JavaScript"><!--

function startclock(){var thetime=new Date();

var nhours=thetime.getHours();var nmins=thetime.getMinutes();var nsecn=thetime.getSeconds();var nday=thetime.getDay();var nmonth=thetime.getMonth();var ntoday=thetime.getDate();var nyear=thetime.getYear();var AorP=" ";

if (nhours>=12) AorP="P.M.";else AorP="A.M.";

if (nhours>=13) nhours-=12;

if (nhours==0) nhours=12;

if (nsecn<10) nsecn="0"+nsecn;

if (nmins<10) nmins="0"+nmins;

if (nday==0) nday="Sunday";if (nday==1) nday="Monday";if (nday==2) nday="Tuesday";if (nday==3) nday="Wednesday";if (nday==4) nday="Thursday";if (nday==5) nday="Friday";if (nday==6) nday="Saturday";

Page 66: Javascript Tutoriallll

nmonth+=1;

if (nyear<=99) nyear= "19"+nyear;

if ((nyear>99) && (nyear<2000)) nyear+=1900;

document.clockform.clockspot.value=nhours+": "+nmins+": "+nsecn+" "+AorP+" "+nday+", "+nmonth+"/"+ntoday+"/"+nyear;

setTimeout('startclock()',1000);

}

//--></SCRIPT></HEAD>

<BODY>

<FORM name="clockform">Current Time: <INPUT TYPE="text" name="clockspot" size="40"></FORM><SCRIPT language="JavaScript"><!--startclock();//--></SCRIPT>

</BODY>

Yipes! This is pretty long, isn't it? Actually, it is most of the script is getting the numbers to do what we require for our clock to look like the one above. Let's take a closer look at what we have added.

More Member Function Calls

We are calling more of the member functions in order to get the extra information. The ones we have added are calls to getDay() for the number of days into the week, getMonth() for the number of months into the year, getDate() for the actual day of the month, and getYear() for the number of years into the century. We assigned them all to variables so we could manipulate the numbers to display what we want. Here are the variable declarations:

var nday=thetime.getDay();var nmonth=thetime.getMonth();var ntoday=thetime.getDate();var nyear=thetime.getYear();

Now we have variables with our new information, but some of them are not quite in the form we want them to be. The only one we do not have to change is "ntoday", which gives us the day of the month- a number such as 1, 2 ,15, 30, etc. So, we know whether it is the first, second, 15th, or 30th of the month. The other variables have values that need changing though.

Page 67: Javascript Tutoriallll

Adjusting the Variable Values

Let's look at the variable "nday". This holds our value for the day of the week. However, the value is a number. Not only that, the numbers are 0-6 rather than 1-7. Changing this to the actual day of the week isn't so bad, we just have to check what the number is, and change the value to "Sunday" if the number is zero, "Monday" if the number is 1, and so on. Here is the portion of the code that does this, using if conditions:

if (nday==0) nday="Sunday";if (nday==1) nday="Monday";if (nday==2) nday="Tuesday";if (nday==3) nday="Wednesday";if (nday==4) nday="Thursday";if (nday==5) nday="Friday";if (nday==6) nday="Saturday";

Now, let's look at nmonth. It is the number of months into the current year. However, instead of starting at 1 and going to 12- it starts at zero and goes to 11. To make it display the traditional number for the month (1 for Jan., 2 for Feb., etc.), we will need to add one to this value:

nmonth+=1;

Remember, the += operator adds one to the value of nmonth. We could have written it as:

nmonth= nmonth+1;

Now, we have to get the year. Our variable nyear gives us the number of years into the current century- the last two numbers of the year such as 98 or 99. One problem- the dreaded Y2K problem. In IE5+, the date actually goes to 4 numbers, to 2000. In NS 4.6 the date flips to 100- not zero! I found the code below works for these two browsers, though I did not check it with older versions- but those may have other Y2K bugs to worry about. So, if the year comes back as 99, I added a 19 in front. If it is between 99 and 2000, I added 1900 to it (100+1900=2000) so NS would work with it. IE just gives back 2000 so if it is more than 2000 it can be left alone.

if (nyear<=99) nyear= "19"+nyear;

if ((nyear>99) && (nyear<2000)) nyear+=1900;

End the Script

All that is left in the main script is to output our values to the text box. This clock used the code below:

Page 68: Javascript Tutoriallll

document.clockform.clockspot.value=nhours+": "+nmins+": "+nsecn+" "+AorP+" "+nday+", "+nmonth+"/"+ntoday+"/"+nyear;

Now, end the function by calling it again after one second:

setTimeout('startclock()',1000);

The HTML, Call the Script

The HTML to display the clock is the same as before. The only additions are the SCRIPT tags and the call to the startclock() function. This is so the clock starts right when the browser knows the text box exists and has the names in the name=" " attributes:

<FORM name="clockform">Current Time: <INPUT TYPE="text" name="clockspot" size="40"></FORM><SCRIPT language="JavaScript"><!--startclock();//--></SCRIPT>

Now you do not need to wait for the rest of the page to load in order to see the clock run. Great, isn't it?

Well, that takes care of the clock for now. Go have fun with it, maybe make some adjustments of your own. Oh, if you see any problems with the Y2K code, or have something that will solve the problem for longer than my code did, or know some code for older browsers, let me know.

Well, that does it for now, let's go on to The Math Object. 

The Math object of JavaScript allows you to perform certain calculations by using method functions of the Math object. Also, it provides a few constants such as pi. The easiest way to get a value is to define a variable and set its value to a property or function of the Math Object.

If you want to use a property, which returns a constant value (such as pi), you would write something like this:

var my_car=Math.property;

You would replace the word "property" with the property you want to use. So, if you want to use the value of pi in a variable, you would use the PI property of the Math object. You would write:

var my_pie=Math.PI;

This returns the pi constant, a number with lots of decimals, or 3.14.....

If you want to use a member function, which performs a calculation, you would write something like this:

var my_house=Math.function(x);

Most of the member functions have one or more parameters, which is what the "x" is for. You can replace x with a number or variable. You would replace the word "function" with the function you want to use. For

Page 69: Javascript Tutoriallll

instance, if you want the square root of a number, you can call the square root member function of the Math object with the number as the parameter:

var my_money=Math.sqrt(2);

This gives back the square root of 2, which is another number with lots of decimals, around 1.41.....

Now that you have seen how little money I have, be sure to take notice that the "M" in Math is always capitalized. The word Math is followed by the dot operator (.), and then the property or member function you want to use.

These are not too difficult to use now that you know how to get to them. Here are some of the properties you can use, these return the constant values:

Math.PI Returns the constant pi

Math.SQRT2 Returns the square root of 2

Math.SQRT1_2 Returns the square root of 1/2

Below is a table of some of the commonly used member functions of the Math object. These functions calculate values based on the parameters you send to them (except the random function):

Method Function

What it Does

abs(x) Returns the absolute value of the variable x.

cos(x) Returns the cosine of the variable x.

log(x) Returns the natural log of the variable x.

max(x,z) Returns the larger of the two variables x and z.

min(x,z) Returns the smaller of the two variables x and z.

pow(x,z)Returns the value of the variable x to the zth power.

random() Returns a random number between 0 and 1.

round(x)Returns the variable x rounded to the nearest integer.

sin(x) Returns the sine of the variable x.

sqrt(x) Returns the square root of the variable x.

tan(x) Returns the tangent of the variable x.

Hopefully, you will find some of these useful in your scripts. We may start using some of these in future tutorials, so be on the lookout!

Well, let's move on to the next section: Using the Math.random() Function. 

Page 70: Javascript Tutoriallll

The random() method function of the Math object allows you to get random numbers for various uses in your scripts. You can make a random quote generator or have another type of random script. The only trick is knowing how to get a random number within the boundary you want, and making it a random integer.

By default, the random function returns a random number between zero and 1. This by itself isn't very useful. Click the button below, and notice that the number in the alert is a long random number after the decimal point:

In that state, you can't really do anything with the number. We want to have an integer between zero and a set number. The first step to fixing this is using multiplication. If you want a number between zero and 4 (5 random numbers), multiply the result of the Math.random() function by 5:

var ran_number= Math.random()*5;

Now, the numbers you get will be between zero and 4- but they still will not be integers. Try the button below and see:

We need these to be integers so we can have just the five random numbers between zero and 4. The next step will finish the job of getting the random number. To clean up those decimals and get just the integers, we use the Math.floor() function (which removes anything after the decimal and leaves the integer portion of the number) for the result. The quickest way to implement this is to place the Math.random()*5 inside the Math.floor() function as its parameter:

var ran_number=Math.floor(Math.random()*5);

You can also use two steps if it seems to make more sense:

var ran_unrounded=Math.random()*5;var ran_number=Math.floor(ran_unrounded);

Now, try this button. You'll see a nice looking integer between zero and 4:

Now, you may be wondering why we want the number between 0 and 4, rather than 1 and 5. When we are ready to make a script that uses this, an array is a handy way of getting to a value. Arrays start counting with an index number of 0, such as:

array_name[0];

Keeping the random numbers in line with the array numbers will save some headaches as to when you should add or subtract the number one to get it working.

Now, let's build a little random quote script that will give the viewer an alert with a random quote on a button click. We already know how to get the random number, we just need to use an array to store some quotes- and make use of them with the random numbers. We'll use 5 random quotes, so we need 5 random numbers. This will keep us with our "between zero and 4" theme. Let's begin by creating a function, and setting up a variable to get a random number:

function get_random(){ var ranNum= Math.floor(Math.random()*5); return ranNum;}

Page 71: Javascript Tutoriallll

This function will simply return a random number between zero and 4. Our next function will call this function and assign the returned number to a variable named whichQuote: this will be the variable we use to get the proper quote from the array we will define. So, let's also define an array here, and set it up with five quotes:

function getaQuote(){ var whichQuote=get_random();

var quote=new Array(5) quote[0]="I love JavaScript..sometimes."; quote[1]="Why are you pushing my button?"; quote[2]="The button you pushed can\'t push you back. You bully, you!"; quote[3]="This alert is here to inform you that alerts are annoying."; quote[4]="Which came first, the button or the alert?"; alert(quote[whichQuote]); }

As you can see, the last line of the function gives the user the alert. The value of the alert is the quote stored in the quote array:

quote[whichQuote]

Remember, the whichQuote variable was assigned a random number between zero and 4 from the get_random() function. So, if the value of whichQuote is 3, you get an alert with the quote from the array at quote[3]. Each time the button is clicked, it is all run again and will assign it another random number.

As for the button, here is how to code it into the body section:

<FORM name="form1"><INPUT TYPE="button" value="Get a Quote!" onClick="getaQuote()"></FORM>

Notice that it calls the getaQuote() function when it is clicked. This gets everything started.

To put it all together, here is the entire script. We can now see how it all works within the document:

<HEAD> <SCRIPT language="JavaScript"><!--function get_random(){ var ranNum= Math.floor(Math.random()*5); return ranNum;}

function getaQuote(){ var whichQuote=get_random();

var quote=new Array(5) quote[0]="I love JavaScript..sometimes."; quote[1]="Why are you pushing my button?";

Page 72: Javascript Tutoriallll

quote[2]="The button you pushed can\'t push you back. You bully, you!"; quote[3]="This alert is here to inform you that alerts are annoying."; quote[4]="Which came first, the button or the alert?"; alert(quote[whichQuote]); }//--></SCRIPT></HEAD>

<BODY><FORM name="form1"><INPUT TYPE="button" value="Get a Quote!" onClick="getaQuote()"></FORM> </BODY>

Now, if you want to try out the script go ahead and click the button below:

You can also use more quotes by making the array larger and adjusting the number you multiply with the Math.random() function. You can turn the random quote script into a script with many more quotes. Just remember that if you want 10 random numbers, multiply by 10. If you want 20: multiply by 20. This will keep your arrays happy, and it will probably keep you happy as well!

Well, that does it for now, let's move on to: Strings with charAt and indexOf. 

To get started with advanced string handling in JavaScript, we will begin by looking at two of the JavaScript methods for strings. These two methods, charAt and indexOf, are used to find out what character is at a certain position in a string and to find out where a character or a smaller string begins within a string, respectively. Before we get to those, we will also want to look at the length method. This gives us the length of a string, which may be helpful when we use the other methods. So, let's go in and take a look at these methods, starting with length.

length

The length method returns the length of a particular string as a number. For instance, if a string is 5 characters long, the length method would return the number 5. To use the method, you will want your string to be placed in a variable. For this example, we will simply assign a string to a variable:

var my_car="Ferrari";

Now, to use the length method, we use the dot operator (.) as the connection. First, we use the variable name. Then, we follow the dot operator with the word "length", which will return the length of the string:

my_car.length

Of course, if we want to use the value it returns, we can assign it to a variable:

var how_long=my_car.length;

In this case, the variable how_long will have a value of 7, since the word "Ferrari" has seven characters. The length method is even more useful if you are using a value entered by a viewer at a prompt or another input area and do not know what the string is. Using this, you can find the length and use it for

Page 73: Javascript Tutoriallll

other purposes, such as showing an error message for strings that are longer than what you want them to be- for example:

<SCRIPT language="JavaScript"><!--function getname(){var yourname=prompt('Enter your name, NOW!','');if (yourname.length > 10) { alert('That name is just too long, give me a shorter one!'); getname(); }else alert('Hi '+yourname+'!');}//--></SCRIPT>

Give it a try with the link below. If you enter a name longer than 10 characters you get an error alert. Otherwise, you get a greeting alert!

Example: Give me your name!

charAt

Using the charAt method, you can find out what character is filling a designated position within a string. Basically, it allows you to find out what character is first, second, third, and so on. The important thing to remember is that when dealing with the position of a character, the count starts at zero, not one. So the first character is actually at position zero.

As with the length method, we assign the string to a variable, and then use the dot operator to call the charAt method. The charAt method takes an argument, which is the position number for the character it should return. So, if we want to find the first character in our "Ferrari" string, we would do it this way:

var my_car="Ferrari";var the_char=my_car.charAt(0);alert('The 1st character is '+the_char+'.');

This would give us an alert telling us that "The first character is F." We can do the same by sending the number 1 as the argument to get the second character, or sending the number 2 to get the third character, and so on.

As for the last character, we can use the length method from above to find out what character is in the last position in the string. Remember, though, that the length function returns the number of characters. The positions start with 0, but length starts counting at 1. So, to get the position of the last character we must use length-1. "Ferrari" has a length of 7, but the last position (count up from 0) is actually 6. That is why length-1 will get you the number for the last position! Here is a little sample:

var my_car="Ferrari";var the_length=my_car.length;var last_char=my_car.charAt(the_length-1);alert('The last character is '+last_char+'.');

Page 74: Javascript Tutoriallll

This time, you will get an alert telling you that "The last character is i." This is fun, isn't it?

indexOf

Now we get to the really fun method of indexOf. This method lets you check for a character or even a small string within the current string, and returns the position at which your character or string begins. Again, remember that the position starts counting at 0, so if indexOf returns zero, it means your character or string begins at the 1st character. Also, indexOf has a useful return value of -1 if the character or string you searched for is not contained within the string. And finally, if the character or string you search for occurs more than once, indexOf returns only the first appearance of your character or string.

First, let's find the 'a'. No problem, again we use the dot operator. IndexOf also takes an argument like charAt does, but this time the argument is the character or string we are looking for:

var my_car="Ferrari";var where_is_a=my_car.indexOf('a');alert('The a is at position '+where_is_a+'.');

Notice the quote marks around the argument of a. This tells the browser to look for that string, which is the type of argument you must send for indexOf to function properly. This code will send back the position of the letter a. The alert will say "The a is at position 4." Look out letter a, you have been found!

Let's now look for the letter 'r' in "Ferrari". As you can see, 'r' is in the string three times. However, only the first appearance will be returned, at position 2.

var my_car="Ferrari";var where_is_r=my_car.indexOf('r');alert('The r is at position '+where_is_r+'.');

Now the alert says "The r is at position 2." The other r's at positions 3 and 5 are not the first, so they are not returned.

What about if we search for something that is not there? Well, indexOf will return a -1. We can use this -1 to tell us that what we are looking for is not there. This can be helpful when you ask a viewer for information, but the viewer does not type the information with a required character or set of characters. For instance:

function get_url(){var your_url=prompt('Enter your web page URL!','');var is_protocol_ok=your_url.indexOf('http://');if (is_protocol_ok==-1) { alert('Error: Your url should begin with http://'); get_url(); }else alert('Thanks!');}

This one checks to be sure the viewer entered the http:// part of the address. If not, it shows the error alert and gives the viewer a chance to enter the url again. Of course, you can cut down on the number of forgotten http:// beginnings by using http:// as the default value for the prompt instead of nothing:

Page 75: Javascript Tutoriallll

var your_url=prompt('Enter your web page URL!','http://');

Of course, the viewer could delete it by accident (or even on purpose), so the check would still be worthwhile. You could even go a step further and be sure that there is at least one dot (.) in the address as well. This way, the viewer would need to have a string plus a dot and hopefully a com or net afterward ( like http://pageresource.com ). We can also check for the http:// as well, here is a sample:

function get_url(){var your_url=prompt('Enter your web page URL!','http://');var is_protocol_ok=your_url.indexOf('http://');var is_dot_ok=your_url.indexOf('.');if ((is_protocol_ok==-1) || (is_dot_ok==-1)) { alert('Error: Your url should begin with http:// and have at least one dot (.)!'); get_url(); }else alert('Thanks!');}

You can try out the script below, type some url and see what it does!

Example

Of course, it is still not going to totally eliminate mistakes or bad urls, (someone could just enter http://.) but it helps a little bit.

As you can see, these methods can be quite useful when dealing with strings. Hopefully you will find a great way to use them for your site!

Well, that does it for now, let's move on to Strings 2: Using Split. 

The split method is a handy way to "split" a string into two or more parts based on a character that divides the parts. The character that divides the parts could be many things-- a comma, a slash, a pipe symbol ( | ), or another of your choice. For example, look at the string below:

var where_is_mytool="home/mytool/mytool.cgi";

Notice that the slashes coud be used as a way to divide the string into three parts. You could separate the home directory, the file directory, and the file name for the program. To actually do this, we can use the split method. As we did with the charAt and indexOf methods, we take the variable name of the string and add a dot-- and then call the split method:

var where_is_mytool="home/mytool/mytool.cgi";var mytool_array=where_is_mytool.split("/");

As you can see the split method takes a parameter, which is the character we wish to use to divide the original string. In this case, it is the "/" character. You will also notice that what we get back will be an array (notice the variable we hold the result in is called mytool_array). This array holds the three parts, with the first part held in a variable called mytool_array[0]. So, the first element is zero for the arrays you

Page 76: Javascript Tutoriallll

create with split, just like many others we have seen. Knowing this, we can now use the parts which we get from the split in some way:

<SCRIPT language="JavaScript"><!--function divide_string(){var where_is_mytool="home/mytool/mytool.cgi";var mytool_array=where_is_mytool.split("/");alert(mytool_array[0]+" "+mytool_array[1]+" "+mytool_array[2]);}//--></SCRIPT><FORM><INPUT TYPE="button" onClick="divide_string()" value="Go!"></FORM>

This one will just give us an alert with the three parts when we click a button. You can see it in action using the button below:

Another thing to remember is that there are times when you will not know how many parts the array will have once it is split (for example, if a viewer enters the information in a prompt). To be sure you get them

all, you can use a loop and the length method to get all of them. For example:<SCRIPT language="JavaScript"><!--function divide_string2(){var my_colors=prompt("What are your favorite colors? (separate with a space)","");if ((my_colors=="") || (my_colors==null)){ alert("You have no favorite colors? Bummer.");}else if (my_colors.indexOf(" ")== -1) { alert("Either you only like one color or you didn't separate with a space."); alert("You entered "+my_colors); }else{var col_array=my_colors.split(" ");var part_num=0;while (part_num < col_array.length) { alert(col_array[part_num]); part_num+=1; }}}//--></SCRIPT><FORM><INPUT TYPE="button" onClick="divide_string2()" value="Go!"></FORM>

Page 77: Javascript Tutoriallll

Notice that the length method returns the number of elements in the array, which is one greater than the index number for the last element in the array. This is why we use < instead of <=, because part_num will not have an element with the index number equal to the array length, it will only have them up to one less than the array length. So, if you entered 3 colors, the array length is 3, but the index numbers within the array start at zero and are 0, 1, and 2.

The example is below, give it a try:

This validates to some degree, but it doesn't keep a viewer from using a space once and then doing something else. It could still not be quite right if someone types in "red greenorange,blue". This would

give back one alert with "red" and another with "greenorange,blue". Still, it will do the job for the most part, and uses some of the things we learned in earlier sections.

Well, that is how to use the split method, I'm sure you can create a more useful script with it. You could use it to grab parts of urls, email addresses, and so on. This will also come in handy in other areas, such as in the use of cookies and form validation.

Well, that does it for now, let's move on to Screen Resolution Detection! 

Newer browsers allow you to detect the user's screen resolution using the screen.width and screen.height properties. This can be a helpful way to send viewers to the right version of your page, depending on their computer's screen resolution.

The properties hold the values of the pixel length of the width and height of the viewer's screen. For example, you could send the viewer an alert when a link is clicked that gives the screen resolution:

<A HREF="javascript:alert('Your resolution is '+screen.width+'x'+screen.height);">Click for your screen resolution</A>

To see this in action, try the link below: Click for your screen resolution

This can be useful if you have a page designed for a screen resolution that is higher than some viewers may have available. For instance, if you had a design that would be viewed most comfortably at a resolution of 1024x768 or better you could set up an if-else statement to send the viewer to the high resolution page if their screen can handle it. If not, you can send them to a low resolution version of the page:

<SCRIPT language="JavaScript"><!--if ((screen.width>=1024) && (screen.height>=768)){ window.location="highres.html";}else{ window.location="lowres.html";}//--></SCRIPT>

Page 78: Javascript Tutoriallll

As you can see, this could help you give your visitors a design that is best for their screen resolution and can allow you to create larger designs without having to leave some of your visitors with horizontal scrollbars.

Well, that does it for now, see you when I write the next section! 

t="previous">Previous


Recommended