IF YOU ARE USING NETSCAPE NAVIGATOR, HIT THE RELOAD BUTTON BEFORE CONTINUING. IT WILL RESOLVE ALL OF THE PROBLEMS THAT OCCURED FROM PLACING MULTIPLE SCRIPTS IN ONE WEBPAGE.
This lesson by no means will teach you JavaScript. This is only an introduction to this programming language and I hope that you can take what you learn here and better understand how to use scripts on your webpages. I believe that it is not vital that professional web designers know JavaScript. Typically if something can be done with JavaScript, then a script has already been written to do it. The trick is finding that script and putting it to use on your page. This lesson will give you an idea of how JavaScript works and how to know what a script is going to do on your page.
What is JavaScript?
This may best be answered by defining what JavaScript is NOT. First, it is not HTML. JavaScript does not use HTML tags or abide by any of the general rules of the HTML programming language. You can however, use JavaScript with HTML on a webpage. Second, JavaScript is not Java. Although JavaScript is often called Java, the two are not the same. Java was developed by Sun Microsystems and is a stand-alone programming language. JavaScript, on the other hand, was developed by Netscape Corporation. Although similar to Java, JavaScript is not a stand-alone language; in order for JavaScript to work, it must be part of a webpage that is being displayed in a browser that understands the JavaScript language. Java alone can be implemented in webpages as a built in program, whereas JavaScript scripts are reliant upon the client (visitor's) computer in order for them to work. JavaScript is really a stripped down version of Sun Microsystems Java language. There are similarities between the two, but they function quite differently. JavaScript is an Object Oriented Programming Language. Think of an object as an individual element (kinda like webpage elements). JavaScript creates and makes changes to these objects.
How Does JavaScript Work?
Once again, JavaScript is not HTML or a version of HTML. It is a distinct, separate programming language. HTML is read and processed by the web browser. When the browser reads JavaScript code within your HTML document, it passes that code on to the client computer, which processes the code, then sends the results back to the browser. For this reason, the computer reading the JavaScript must have an API (Application Program Interface), a program that interprets the script. This comes with Windows and Netscape. The API is also called the Java Virtual Machine or VM.
Also, JavaScript is a very precise language. In HTML, rules are made to be broken. There are usually several ways to write one line of HTML. The formatting rules of HTML are also very loose. Your browser doesn't really care the order in which tags are entered and often if you use improper coding, the webpage will still display properly. JavaScript is just opposite. The coding must be written precisely or the script will not work.
JavaScript Basics
Here is a typical JavaScript:
<SCRIPT LANGUAGE="JavaScript">
document.write("<FONT SIZE='5'>This Is Big Text</FONT ><BR>")
</SCRIPT>
would display
The rules:
OK, let's analyze the above script. The SCRIPT LANGUAGE="JavaScript" tells the browser that the next section is JavaScript code and to send it to the computer to figure out what to do with it, then wait until the computer sends back directions on what the script does. THIS TAG IS REQUIRED!!!
The middle section is not too hard to figure out. In this script, document.write means to write or display something within the web page document. Then, within parentheses is what should be written; in this case, a line of size 5 text. Last, is the closing script tag, which tells the browser to keep reading the HTML of the page.
In this sample script, document is what is called an object and write is called a method. Objects are usually elements, or something that exists and methods are actions taken upon objects. This script says to write to the document the text contained between the parentheses. Notice the use of double quotes around the HTML section that is being written and the use of single quotes within the HTML. Did the JavaScript make the text big? No, the script just wrote or entered the HTML to the web page document. The browser then read that HTML and made the text big.
Functions
Functions can be thought of as a set of JavaScript commands. When you create a function, you assign a name to a set of JavaScript commands.
For instance, if I wanted to repeat the previous example three times, I could write the following:
<SCRIPT LANGUAGE="JavaScript">
document.write("<FONT SIZE='5'>This Is Big Text</FONT><BR>");
document.write("<FONT SIZE='5'>This Is Big Text</FONT><BR>");
document.write("<FONT SIZE='5'>This Is Big Text</FONT><BR>");
</SCRIPT>
Which would display:
Notice the semicolons at the end of the line. Each separate command in JavaScript should be separated by a semicolon. Remember, don't allow a command to be broken or wrap to a new line. However, rather than repeating the same code multiple times, I could have made the document.write command a function, then used that function three times. Here's how I would do it:
<SCRIPT LANGUAGE="JavaScript">
function jared() {
document.write("<FONT SIZE='5'>This Is Big Text</FONT><BR>");
}
jared();
jared();
jared();
</SCRIPT>
The first thing I did was give a name to the function, jared() in this case. The function name can be most anything you want (except words that have special meaning in JavaScript). It must have the () at the end. I then defined that function with everything between the curly brackets. Again notice the semicolon. Now, jared is equal to the document.write command. To call a function or make it run, you just call it my name. Each time I wrote jared() it made the function run. The cool thing about functions is that once a function is defined, I can use it anywhere in the page. Usually functions are defined in the head section of the document, then they are called or used in the body of the webpage.
Comments in JavaScript
There are several ways to add comments to your JavaScript code. Comments are used for information that you do not want to be an actual part of the script, but do want to be displayed with the script. You will often see copyright or author information within comments. Normal HTML comment tags will not work within a script. Here are a few ways to add comments.
// - the single line comment will comment out the line that they begin only. You can add as many as you choose, but each line must begin with //.
/* - the multiple line comment will make everything that follows it a comment until the browser reads */. Be sure to use the correct forward slash.
JavaScript Events
JavaScript is an object oriented programming language. That means that it uses objects (some element in the browser window) and performs methods on that object. In the examples above, the object was document. Document is the entire web page. We applied a method (write) to it (written document.write in JavaScript). There are many object that JavaScript can manipulate. We already know document is one. Another object is called window. Window is the entire browser window. The window object contains the document object. The document object contains other objects, like images and stuff. Each unique object has different methods that can affect it. We'll learn more about objects later.
Now that we have an idea how objects and methods work, let's learn about events. Events are not actually scripts. They use the JavaScript language, but have actually been built into HTML, kinda like style sheets have been. Because they are not scripts, they do not require the SCRIPT tags. Instead, they are added directly to existing HTML tags. An event is usually triggered by the browser itself or the visitor. Events allow for interactivity between the web page and the visitor.
The most popular event is onMouseOver (notice the capitalization). This is an event that is triggered when the visitor places the mouse over an HTML element.
<A HREF="http://smithplanet.com" onMouseOver="window.status='JavaScript
is fun'; return true">
Put Mouse Here</A>
would display
Put Mouse Here
You don't need to click the link. Move your mouse over the above link and look at the status bar at the bottom of the browser window.
OK, let's take a look at this event. We begin the event with a typical anchor (link) tag. Then we add the event information - onMouseOver. onMouseOver is NOT an attribute of the anchor tag, but it kinda works like one. window.status looks like another object/method combination (remember document.write). Yes, window IS an object, but status is not a method, it is called a property. A property is a part of or characteristic of the object it is associated with. Here, status is a property of window, or a part of the window - the status bar.
Properties and methods look very similar, but they are very different. It may help you to differentiate if you remember that methods are usually verbs, like write and get. Properties are usually nouns.
Back to our example. window.status is also equal to something, 'JavaScript is fun' (the single quotes are required). The window's status bar will contain that text. The semicolon indicates the end of the command line. Return true controls when the event takes place. When the browser reads return true, it will check to see if the status bar is available and display the text you specify. If you omit return true, then the browser will add the text to the status bar after the mouse is removed from the link. While the mouse is over the link, the status bar will display the URL of the link, as is the default. Here is the same event with return true removed. Put Mouse Here Be sure to place the entire onMouseOver section on one line or the event will not work.
Once I set the window.status, it remains until told to display something else or the visitor leaves the page. Notice that the status still reads JavaScript is fun. To remove this text from the status bar once the mouse is removed from the link, add the onMouseOut event to the anchor tag.
<A HREF="http://smithplanet.com" onMouseOver="window.status='JavaScript
is fun'; return true"
onMouseOut="window.status='';return true">
Put Mouse Here</A>
would display
Put Mouse Here
Notice that I have added two events to the same tag. This is OK, as long as
they don't conflict. The onMouseOut event will change the window status to display
'' or nothing (THOSE ARE TWO SINGLE QUOTES, NOT ONE DOUBLE QUOTE). When you
remove your mouse from the link, the status bar becomes blank.
HINT: Many people like to see the URL of the page that the link will go to.
ANOTHER HINT: The onMouseOver event can be added to the IMG tag to give information
about an image, but only Internet Explorer will display it.
Besides onMouseOver and onMouseOut, there are many other events you can add. Here are a few:
onClick
<A HREF="http://smithplanet.com" onClick="alert('Going so soon?');">Click Here</A>
would display
Click Here
onClick is an event that is triggered when something is clicked with the mouse. Notice that this event triggers a method called alert. Alert will create a pop-up box. You can use it to give your visitors additional information. The text between the single quotes will appear in the alert window.
HINT: Do not use single quotes within any text in your scripts or events. For instance, I'll, you'll and it's all contain a single quote (apostrophe) and will cause an error. Use I will, you will, and it is instead.
A popular use of this event is with form buttons. It is triggered when a form
button is pressed.
<FORM>
<INPUT TYPE="button" VALUE="Yahoo!" onClick="parent.location='http://yahoo.com'";>
< /FORM>
would display
In this example, I used something new - parent.location. This means a link. In this case, the event will open a link in the browser window (called parent in this case, because the browser is the parent to, or contains, this button). Location is the link itself.
Prompts and Variables
Prompts are used for getting information from visitors. Variables are something that you can assign a value to. For instance, if you create a prompt that will ask your visitor their name, you can assign their name to a variable called name. Once you have a value for a variable, you can use it over and over.
<SCRIPT LANGUAGE="JavaScript">
var yourname = prompt ("Please enter your name.","");
document.write("Hello " + yourname + ". Welcome to my page!");
</SCRIPT>
Notice how I moved to the next line only after the semicolon. To see this script in action, click here.
OK, we're out of the event mode and back to the script mode, which means we are using the SCRIPT tags again. You might be asking, "Where do you put this SCRIPT tag?" Well, really you can put it wherever you want. Typically it is placed within the HEAD section of your HTML document so that it loads before the rest of the page, but it does not have to be. Placing it in the head also can aid in editing. If the SCRIPT contains a document.write command, then it must be placed in the page where you want something to be written. If the script is not vital to the page itself, it can be placed at the end of the HTML, before the closing BODY tag, so the rest of the page displays faster.
Alrighty, back to our script. After the opening SCRIPT tag, the first thing we see is var yourname =. Var stands for variable. The variable name is yourname (I could have made it about anything) and it will be made equal to something. Then the script contains prompt ("Please enter your name.","");. This section of the script will open a prompt window which will ask for some input. The text between the first set of quotes is the text that will display on the prompt window. If you add any text between the second set of quotes, this will appear in the text box of the prompt when it appears. I have left this blank, so the input box will be blank until the user enters something. If we examine the whole line, we see that we are setting a variable (yourname) to be the input of the prompt (whatever the visitor types). See the semicolon at the end of the line, it means this command has ended.
The next line is a simple document.write command. It says to write the text "Hello ", then the value for the variable yourname (whatever the user had entered), then ". Welcome to my page!". Variable names are case sensitive as well, so if I had told the script to write Yourname, it would not have worked. Anything between the parentheses after write will be written in the web page. Notice the use of double quotes. Double quotes surround text that I want to be written to the web page. The plus sign (+) is used to connect sections of the text.
This is an excellent way to get input from your visitors for customizing your webpage. Once you have defined a variable, you can use it again and again throughout your page, just add the following anywhere you want it to appear:
<SCRIPT>document.write(yourname)</SCRIPT>
Just be sure that you specify the correct variable name. In the example above, it would display the visitors name anywhere this script is found. Notice that I didn't specify LANGUAGE="JavaScript". It is optionaly, but the browser will know which scripting language you are using because you specified it previously in the same document.
You can also use variable with functions, like this:
<SCRIPT LANGUAGE="JavaScript">
function addnumbers() {
var x= 3;
var y= 2;
var result= x + y;
alert(result);
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Add Them Up" onClick="addnumbers()">
</FORM>
I first named the function addnumbers(). Anything between the curly brackets is equal to that function name. I then set the variable x equal to 3, and y equal to 2. I then set the variable named result to the sum of x and y, or 5. I then entered an alert statement which would display the variable named result. The button is set to display the function addnumbers() when it is clicked. Go ahead and try it!
You can also use functions with other events like:
onMouseOver="addnumbers()"
onLoad="myfunkyfunction()"
onLoad would be added to the BODY tag to make the script load as soon as the webpage is loaded. The onLoad event can be used for any JavaScript command. You can also use onUnload. This will make the script load as soon as the visitor leaves the page.
<BODY onUnload="alert('Goodbye')">
would make an alert window display when the page is exited.
Additional Properties
We have already discussed a few properties of objects. One was the status property of the window (window.status). There are several other properties that you can use. Here are a few:
document.bgColor - the background color of the webpage.
document.fgColor - the color of the text.
document.linkColor - the of the links on the page.
document.alinkColor - the color of active links.
document.vlinkColor - the color of visited links.
document.location - the URL of the webpage you are viewing.
document.referrer - the URL of the webpage you viewed previous to this page.
document.title - the title of the webpage.
document.lastModified - the date the HTML file was last modified.
navigator.appName - the name of the web browser (Internet Explorer or Netscape).
navigator.appVersion - the version number of the browser being used.
navigator.appCodeName - the browsers code name (usually Mozilla for both browsers).
navigator.userAgent - the HTTP header (contains the browser code name and operating
system used).
history.length - total number of pages viewed by the browser in the current
session.
And these are only a few of them!! You can also use these objects and accompanying properties to get information about the visitor, display information about the visitors browser, or customize your webpage. Here are a couple examples:
<B><SCRIPT LANGUAGE="JavaScript">
var address = document.location;
var backcolor = document.bgColor;
var lastpage = document.referrer;
var browser = navigator.appName;
var version = navigator.appVersion;
document.write ("The webpage is located at " +address+ ". Its
background color is " +backcolor+ ". ")
document.write ("You are using " +browser+ " version " +version+
". You came to this page from " +lastpage + ".")
</SCRIPT></B>
would display
OK, let's take a look at this. Typically it is easier to assign variables to these properties, as I have done, rather than calling the properties directly from the document.write command. Notice my use of spacing between sets of double quotes to get spaces to appear correctly. Spaces around the plus signs are ignored. I also surrounded the script with bold tags to make the results bold.
You can even collect variables and make them equal to some properties. Here's an example:
<A HREF="" onMouseOver="var bg = prompt('Enter a background color!','white');document.bgColor=bg">Put your mouse here!</A>
This EVENT (not a script - no SCRIPT tags) will be triggered onMouseOver. First, it sets a variable name (bg) equal to the input of a prompt. The default value of the prompt is white. Then, it sets the property document.bgColor equal to that variable, thus changing the background color of the page. Pretty cool, eh? I didn't enter anything in the HREF attribute, in case you decided to click on it.
Creating Objects and Using Methods
From above, we learned that objects are usually elements or items, and methods act upon objects. There are many objects that already exist, such as document, which is the web page document. The browser itself is also an object, called window in JavaScript. Every method must have an object to act upon, like write acted upon document in a previous example (written document.write in JavaScript). Sometimes we want to use JavaScript to do something, but there isn't an existing object that we want to use, so we can create our own object that can then be acted upon by methods.
<SCRIPT LANGUAGE="JavaScript">
WebTime = new Date();
document.write("Today's date is " + WebTime.getMonth()+ "-" + WebTime.getDate()
+
"-" + WebTime.getFullYear() + ". You came here at " + WebTime.getHours() +
":" + WebTime.getMinutes())
</SCRIPT>
would display:
ALL OF THE SECTION FROM THE document.write LINE UNTIL JUST BEFORE THE CLOSING SCRIPT TAG SHOULD BE ON ONE LINE OR THE SCRIPT WILL NOT WORK
OK, let's not panic. It's not that hard to figure out what this script does. First thing I did was add the SCRIPT tag to start the script. The next line creates a new object named WebTime. When you create objects you can name them virtually anything you want, as long as it isn't an existing object. I set WebTime equal to new Date(). The semicolon indicates the end of a line of the script. Notice the capitalization of Date() and the parentheses. Date() is the current date and time in which the script was run, it gets this from the client computer. So, in the second line, I created an object named WebTime and made it the current date and time.
Now that I have an object (WebTime), I can now act upon it with methods. The third line began with document.write. Another object and method. I did this so that the results of the script are displayed. Anything between the parentheses after write will be written in the web page. Notice the use of double quotes. Double quotes surround text that I want to be written to the web page. The plus sign (+) is used to connect sections of text.
WebTime.getMonth() is another object/method combination. Remember that WebTime is really the date and time set in the first line. The getMonth method (notice capitalization) will extract the number of the current month from WebTime and display it. The "-" tells the script to write a dash. WebTime.getDate() will extract the date from WebTime and display it. See how multiple methods are acting upon the same object (WebTime).
A Few Pointers:
Opening New Windows
One of the more common uses of JavaScript is the opening of windows.
<SCRIPT LANGUAGE="JavaScript">
window.open('popup.htm', 'welcome', config='height=300,width=300')
< /SCRIPT>
The above script will open a new window that is 300 pixels by 300 pixels and will contain the file popup.htm. The name of this window will be welcome. The name is important, because you can do different things to that window by using its name. Notice the part after config= has no spaces. Each property of the new window is separated with a comma. You can also add the following properties to the config section to add new things to the window, just separate each one with commas.
scrollbars=yes
resizeable=yes
toolbar=yes - the toolbar has the back, stop, and home buttons.
menubar=yes - the File, Edit, etc. menu.
location=yes - the location bar is where you type in URLs.
status=yes - displays a status bar on the window.
directories=yes - the bar at the top that contains bookmarks, etc.
If you do not add these to your script, they will not appear. The default is NO. You may also use 1 for yes and 0 for no.
You can also add the window.open command to any event.
<A HREF=""
onMouseOver="window.open('popup.htm','welcome',config='height=300,width=400,
toolbar=yes')>
Put your mouse here.</A>
would display
Put your mouse here.
Inside of the little popup window, I added a link to close the window. It was also an event:
<A HREF="" onClick="self.close()">Close this window</A>
Image Swaps
Another frequent use of JavaScript is image swapping, flipping, or roll-overs. This is usually done by having one image replaced by a second one when the mouse is place over the image. This is great for menu items or any graphical link. Here is an example:
Put your mouse over the image.
<A HREF="http://smithplanet.com"
onMouseOver="document.mypic.src='smithon.gif'"
onMouseOut="document.mypic.src='smith.gif'">
<IMG SRC="smith.gif" BORDER=0 NAME="mypic"></A>
Let's analyze this event. First, we have the anchor tag set to link to smithplanet.com. Next, we add the onMouseOver event. It is set to change document.mypic.src to be the image smithon.gif. Remember when we talked about objects, well this is a object.object.property command. It says to change the object named mypic within this document object to have a source (src) of smithon.gif. Now take a look down at the last line of the event. Its a typical image tag, but see the NAME="mypic" attribute. This is telling the script that this image (smith.gif) is called mypic (you can name it anything you want). So, document.mypic.src='smithon.gif' tells the browser to change the source of the image named mypic within this document to smithon.gif. This is the image you see when you place your mouse over the original image. It changes, or rolls over to the new image - smithon.gif. The onMouseOut event changes the source of that image back to smith.gif (the original image) when the mouse moves off the image. Pretty simple, eh?
You can even use javascript to preload the images that will used in the swap before you put your mouseover them. To do this, you would set up a function that would preload and name each of the images. Then, when they are needed, the event will call for them by name. If you are using larger file sizes in your image swaps, it is best to preload them.
Whew!! That is all for this lesson, but it is not even remotely all there is to know about JavaScripting. There are hundreds of sites on the Internet that offer free scripts for your use. Hopefully this lesson will give you an idea how they work and will help you implement them on your site.
Go to javascripts.com - probably the largest and easiest to use javascript resource on the planet.
Back to Homepage.