Lessons | previous | next |

27. A Wee Dose of JavaScript

Just a spoonful of JavaScript...

It won't hurt...

It may make your web feel better...

Be careful! Don't gulp it!


Please be aware of the tremendous differences between Java, a programming langauge, and JavaScript, a scripting language. Too often people use them interchangably. Java was developed by Sun Microsystems as a computer platform independent programming language for creating small applications, or "applets" that could be part of a web page as well as being a stand alone desktop program. Java applets are like small, self-contained programs, that you can use without seeing or even caring about what is inside of them (we will in a later lesson show you how to find and use Java applets).

The downside of Java is that to create your own applets, you must learn a pretty complex programming language or try to use some of the newer software tools that make the coding less difficult. The other downside is that many Java applets can take a disturbing amount of time to download and run, essentially stalling your web page until it "loads" (in our opinion, waiting to load a scrolling banner is not too many notches above the <blink> tag!).

Originally named "LiveScript", JavaScript was developed by NetScape as something quite different. It was renamed because of structural similarities to the Java programming language. To create JavaScript you simply type its commands interspersed with your HTML and the browser follows the commands as it tries to format the web page.

Hopefully by now you have a sense that as a web browser reads in the HTML code for a page, it starts assembling and displaying the page layout from the top down, so that as a page may partially display even as the browser is reading in the later parts of the HTML document. As each HTML code is read in the browser reacts and formats, without asking any questions.

When the web browser encounters some JavaScript code, it starts interpreting it line by line. But the JavaScript code can instruct the browser to do different things under different situations, or build in some functionality that is not set in motion until the user does something on a page. JavaScript can even create HTML content on the fly, so you can have it do something like print a different HTML message depending on what day of the week it is or changing the background to a random color every time you reload the web page.

So think about JavaScript as a way to add a little bit more brains to your web page. While not as difficult to learn as a pure programming langauge like Java, to use JavaScript is to take a step in complexity up from HTML formatting.

In this lesson we will learn a few small doses of JavaScript that you can use right away in web pages. In another lesson, we will see how it can be used to process your web page forms.

Putting JavaScript in its Place

Where Javascript code goes depends on what it needs to do. As we will see, sometimes we will place JavaScript code inside the <HEAD>..</HEAD> of your HTML file. Other times it sits inside your HTML content. And in other instances, it is added to other HTML tags to initiate "events" triggered by the person interacting with your web page.

The basic approach for writing most "doses" of JavaScript reads like:

  <SCRIPT LANGUAGE="JavaScript">
  <!-- hide from JavaScript impaired browsers
  
  // This is a JavaScript comment. It is not interpreted
  
    JavaScript statement1;
    JavaScript statement2;
    JavaScript statement3;
    
  // done hiding -->
  </SCRIPT>
  
  <NOSCRIPT>
    Content for browsers that cannot deal with
    JavaScript
  </NOSCRIPT>

This is the most reliable way we have found to set up JavaScript so that it works well in most environments. All of the functionality is defined by "statements" between the <SCRIPT>...</SCRIPT> tags. The lines shown in red that are inside of these tags protect the code from displaying if the viewer's browser cannot understand JavaScript. Remember that if a browser does not know what the tag <SCRIPT> means, it will ignore it. The lines in red:

  <!-- hide from JavaScript impaired browsers
     :
     :
  // done hiding -->

enclose the JavaScript statements inside an HTML comment tag so they will not be displayed. The browser would march on, ignoring the <NOSCRIPT> and </NOSCRIPT> tags (again, ignorance is bliss) but it will display the content in between these last two tags.

Now if the browser knows JavaScript, it begins interpreting the code line by line. In JavaScript, lines that begin with either <!-- or // are interpreted as comments, and ignored. The browser looks at all of the other statements, which are step by step instructions, and does as it is told to do.

NOTE: Each JavaScript statement must end with a semi-colon (;) which is how the browser knows it is time to do whatever that line told it to do.

JavaScript says Hello

Probably the simplest JavaScript command is one that displays an alert message-- text that appears in a "dialog" box in the middle of the screen that typically causes the computer to beep and requires you to click an OK button to return to what you were doing. For example, see what happens when you click the button below:

The command to make this happen looks like:

  alert('JavaScript here, boss! What do you want?');

Now if we simply inserted this into our HTML file like:

  <SCRIPT LANGUAGE="JavaScript">
  <!-- hide from JavaScript impaired browsers
     alert('JavaScript here, boss! What do you want?');
  // done hiding -->
   </SCRIPT>

More typically, as with the button above, you want this JavaScript command to happen when it is triggered by an "event" such as the viewer clicking the mouse or even moving the mouse over different parts of the screen. We'll learn more about events as we go.

Objects

Now we will throw some more programming jargon at you! Don't recoil in horror!

JavaScript references an object model for the web environment. What does this mean? Think of it as a family tree structure that as you read it moves from left to right but really references things structure from most global to more specific.

Huh?

The big "parent" is the "navigator"- it has many different "properties" that describe more or less the web browser you are using, i.e. what kind (NetScape, Microsoft, etc) and version number. Below is the "window" object that describes the properties of one web window, with its own special properties. Next down is the "document" object, that describes information about a particular web page, say its URL, the time it was last changed, how many links there are in the page. And within the document object are many more objects that we will see soon.

So in JavaScript we often have to refer to things by where they are in the object family tree, like:

 window.document.form[3].choices.options[2]

which would refer to some property of "options" contained within something else called "choices", which is part of one "form" inside the document of a window. So from left to right this object model goes from biggest to smallest objects, each one separated by a period. The things in square brackets ([x]) represent arrays, or collections of similar objects, so that the example above, the document has at least 4 forms since we are referring to the 3rd one (it gets confusing because JavaScript starts counting many objects starting with 0 rather than 1!).

Sometimes we can use this type of structure to "test" or get some value from our web page environment, known as properties. Other times, we use this structure to change these values or properties.

27a. JavaScript : Alerts and Rollovers

You've tasted it...

let's make alert messages...

generate mouseover messages...

good!


Our first dose of JavaScript is to write a command inside a hyperlink tag to do something when it is clicked. These allow our links to do more than just transfer us to another document:

  <a href="#" onClick="JavaScript Statement">link text</a>
NOTE: We have written this link so that it points to an empty anchor link (#) inside the same document. If we leave a file name or a URL inside the link, the browser will load this document after it completes its work. We want the current document to stay in place.

The listed JavaScript statement will be done when the viewer clicks the hypertext link. The onClick="..." event is triggered by a mouse click. Note the "C" must be capitalized! Also, see how the JavaScript code is enclosed in the double quotes that define the onClick event, while the alert message string uses single quotes.
list to read:

<li><A HREF="#" onClick="alert('A caldera is a circular shaped 
landform depression caused by the eruption of a large, near surface 
body of magma.')">caldera</A>
<li><A HREF="#" onClick="alert('Vesicularity is a measure how much 
of a rock volume consists of air chambers.')">vesicularity</a>
<li><A HREF="#" onClick="alert('Pahoehoe is a type of basaltic lava 
flow texture that comes from the Hawaiian word for smooth and 
ropy.')">pahoehoe</a>
<li><A HREF="#" onClick="alert('Rheology is the study of how 
materials deform.')">rheology</a>
<li><A HREF="#" onClick='alert("A lahar is a mudslide generated 
from the flanks of a volcano. Some say it comes from the 
phrase \"Look Out!\" in the Indonesian language.")'>lahar</a>

Look carefully at the way quote characters are used in the onClick part of the tag. The entire JavaScript command must be enclosed in a set of quotes. And the alert command itself must include another string that is in quotes. We use single quotes and double quotes for this purpose, and it does not matter which one we use:


<A HREF="#" onClick="alert('You are the boss!')">tell me something</A>

will act exactly like:


<A HREF="#" onClick='alert("You are the boss!")'>tell me something</A>

Why bother? Let's say that the message you want to display in the JavaScript triggered alert needs to contain a quote as a character. JavaScript needs to know that the quote means just a quote and not part of the JavaScript instruction. We can do this by putting the forward slash (\) in front of the quote character' known in techie terms as "escaping" the character.

In our example above, we may want the words Look Out! in the last list item to have quotes around them. If we want these to be single quotes, we would use:


<li><A HREF="#" onClick="alert('A lahar 
is a mudslide generated from the flanks of a volcano. Some 
say it comes from the phrase \'Look Out!\' in the Indonesian 
language.')">lahar</a>

but if we want double quotes, we have to swap our uses of single and double quotes like:


<li><A HREF="#" onClick='alert("A lahar 
is a mudslide generated from the flanks of a volcano. Some 
say it comes from the phrase \"Look Out!\" in 
the Indonesian language.")'>lahar</a>

Some MouseOver Action!

So far we have learned how to use JavaScript to do something when the viewer clicks a hypertext link. We can add another feature to our hyperlinks to do something just when the viewer moves their mouse over the linking text (without clicking the link).

The normal behavior for this action is that the web browser displays in its status bar (the area usually at the bottom left corner of the browser window) the URL that the link leads to, like what you see if you move your mouse over, but do not click on, this link to our tutorial.

With JavaScript, we can create a custom message that is displayed instead of the link's URL, like this second link to our tutorial. Clicking either of this links will do the expected; transfer you to the web site specified in the hyperlink's URL.

The JavaScript format for adding this feature is:


  <a href="xxxx.html" 
      onMouseOver="window.status='text of custom message'; 
      return true">linking text</a>

The JavaScript event that triggers the custom message is onMouseOver="..." meaning the hypertext link says "when the mouse is over me, do this". There are two different JavaScript function statements here, separated by a semi-colon (;).

  1. window.status='text of custom message';
    This is the JavaScript command that says, "Display in the status bar everything between the quotes".

  2. return true
    
    This is a "message" that must be sent back to the browser to let it know we are done. We cannot explain why exactly this is needed, but we can tell you that it will not work unless you include this!

If your JavaScript is working, as you move the mouse over the image on this page, the status bar will display the custom message that describe the link, rather than the URL.

NOTE: As of April 1999, this technique of using onMouseOver inside the <map>...</map> tags does not work on Microsoft Internet Explorer 5.0 web browsers.

Using the mouseOver technique can be an effective feature of your web site, but keep in mind that sometimes it is more useful for the person looking at your site to know the URL where the link leads to (perhaps so they can guess the organization that owns the web site from its URL)-- the onMouseOver message hides this information. Use it where it makes sense for your web site design and what you can determine are the needs of the visitors to your site.

27b. JavaScript : Dynamic Content

Let's Increase our Dosage...

write dynamic content to a page...

different messages for different conditions...


We have reminded you before that as an HTML document loads into a web browser, it is interpreted as the browser reads in more data. For HTMl, this means that as soon as the browser gets enough information to display something, it tries to do that, even as it reads in the remainder of the document.

When we refer to dynamic content that you can write in JavaScript, that means that the web browser can do more than just "read and display", "read and display"... as it reads in JavaScript code among your HTML, it can make decisions based upon the way the code is set up, test against some built in functions, and then write different HTML code according to its programmed instructions. It may even be programmed to do something randomly different every time the page loads.

It makes your web pages a bit more "intelligent" than just sitting there looking pretty!

We can use JavaScript to write any other kind of HTML content using the format:

  document.write('xxxxxxxx xxxxxxxxxx');
  document.write('xxxx xxxxxxx xxxxxxx xxxxx');
  document.write('xx xx xxxxxxxxxxxx xx');

Each line of this code writes a chunk of HTML, that is everything inside of the single quote characters. This series of JavaScript statements:

  document.write('<h1>Wide World of Cheese</h1>')
  document.write('<b><i>Not everyone in this world likes cheese');
  document.write('as much as I!<i></b><br> -- Colby Jack (1903)');

will produce the exact same display as this chunk of HTML:

  <h1>Wide World of Cheese</h1>
  <b><i>Not everyone in this world likes cheese 
  as much as I!<i></b><br> -- Colby Jack (1903)

Now if this was all there was to JavaScript, we would not even be trying to teach it to you! JavaScript provides other types of information that you can display that is not available via HTML. There are built in functions that can provide the current date and time, information about the user's web browser, and more as we will soon see. But even more than this, we can set up logical statements to test, so that we can do things like:

If today is Tuesday or Wednesday and the time is after 12:00 PM then display this custom message morning greeting; but if it is before 12:00 PM, then display this different message for the afternoon. But if it is Friday, at any time, let's display a different type of message no matter what time of day it is. Any other day or time, just display a standard "Have a nice day" message.

JavaScript code gives us some flexibility to create dynamic content that can behave and display differently to the viewer.

The first thing we will do is to write a series of JavaScript statements that will create the footers of all of our documents-- but unlike the ones to date that we have written by hand, this same block of HTML/JavaScript can be cut and pasted into every document but will also dynamically print (with examples for this page shown in parentheses):

Not all web servers provide accurate document modification dates, item (c), and typically when you are testing documents on your desktop computer, you will not be able to get this information and it would print some erroneous date like January 1900. We will show you how to test for these conditions. Item (d) is extremely useful because if we were to move our web pages to different web servers or re-arrange our site, the URL would be updated automatically.

The template for our "standard" web page footer for the Volcano Web project looks like the code below. We'll present it first section by section with some explanations. It's not critical that you understand exactly how it works, since when you incorporate it into your working pages, it will be simply a cut and paste operation.

JavaScript Footers
HTML code explanation
<!-- start of Volcano Web standard footers -->
<SCRIPT LANGUAGE="JavaScript">
<!-- hide scripts from old browsers
Marks the beginning of the footer area, with proper JavaScript tags
document.write('<p><hr>
<FONT FACE="helvetica,arial" size=-1>
<i>Volcano Web:</i> <B>');
Horizontal rule, begin text font size and main web site title
document.write(document.title + '</B><BR>');
Write the current document title
document.write('created by Lorrie Lava, ');
document.write('<A HREF="mailto:[email protected]?subject=' 
+ document.title + '">');
document.write('[email protected]</A><br>');
Credits for page with an e-mail link that automatically inserts the page title into the subject line.
document.write('Volcanic Studies, 
<A HREF="http://www.bigu.edu/">');
document.write('Big University</A><p>');</tt></font>
More static content.
// append a modification date only if
// server provides a valid date
if (Date.parse(document.lastModified) > 0) {
  document.write('<B>last modified: </B>' 
  + document.lastModified + '<BR>');
}
This looks tricky. We have set up a conditional test on the value that is returned by document.lastModified, and if it is valid (a non zero return from a function we use called Date.parse, we write the modification date. If we do not get a valid date, this whole block is ignored.
document.write('<B>URL: </B>' 
  + document.location.href + '</FONT><P>');
Write the URL of the current document given by the value returned by the JavaScript variable document.location.href
// done hiding from old browsers -->
</SCRIPT>
<!-- end of Volcano Web standard footers -->
End of the footer code block.

Most of the dynamic content in this examples comes from "properties" of different JavaScript "objects", namely in this case the document object. Each HTML document has built-in identifying pieces of information-- namely it's title, date of last modification, URL, etc. We can query the document object to get and then use this information.

Information we are writing to the page using document.write that is fixed content (strings of text in quotes) and information that is stored in JavaScript variables, like document.title, we join with the "+" sign:

 'Here is some fixed <b>HTML</b> text for the page:' + document.title + '! Nice, eh?'

The "+" sign joins the text together into one longer string, so if we were using it in this lesson page, we would see:

sample web page
Here is some fixed HTML text for the page: 27b. JavaScript- Dynamic Content! Nice, eh?

Our JavaScript footer also uses a "conditional" test ("if this then do that") for the modification date, that looks like:

  if ( some condition to test ) {
    JavaScript statement1;
    JavaScript statement2;
          :
          :
    JavaScript statementN;
  }

which means that if the condition test in the first line's parenthesis results in a TRUE value, we would follow the steps inside the "{" and "}" brackets; if the test is FALSE, we skip these statements. With the power of JavaScript, we can construct very complex conditional tests, but for now we will keep it simple.

More Dynamic Content

Now we will show you even more things to do with JavaScript. Another built-in functionality is the ability to use the viewer's computer to get the date and time (assuming they have it set correctly!). We can use this to "stamp" a greeting on the front page. We could write "Good Morning!", "Good Afternoon!", "Good Evening!", or "Isn't it Late to be At the Computer?" depending on what time of day the function returns to us through JavaScript.

The first thing you have to do is to create a Date object in JavaScript:

  var today = new Date(); 

Now we have something called today that we can reference to get information about the date and time. JavaScript stores this information internally as something like the number of seconds since a reference date such as January 1, 1900. But the JavaScript Date object has properties that allow us to get the month, day, year, hour, minute, second, etc.

One of the easier object properties to use is Date.toLocaleString() which will display the date in accordance to the settings of the user's computer (since there are different conventions for displaying dates in other countries). So we could write code like:

  var today = new Date(); 

  document.write('According to my JavaScript watch, it is ' + today.toLocaleString() )'

which would display like:

If you reload this lesson page, the time on the display will change. Note that the date format returned is dependent on the type of computer.

JavaScript offers other information about the web browser that the viewer is using, via the navigator object, so we can test which web browser it is (NetScape, Internet Explorer, etc) as well as which version. This is useful if you are using features in a web page that require certain web browsers-- you can use JavaScript to "test" the set up and display information specific for different browsers or versions.

27c. JavaScript : Window Openers

So you want to open Browser Windows?

JavaScript Does Windows...

Where you Want Them, How big You Want Them, and with What Browser Buttons You Choose...

In lesson 25, we learned how to add a TARGET option to a hyperlink so that a mouse click would load the link in a new browser window. You may have noticed that this second window opens with the same web browser buttons and fields as the original window, and that it is usually the same size as that first window.

With JavaScript we can write code that creates a new window of arbitrary size, and we can instruct it not to display the URL field or the web browser navigation buttons. Furthermore, for 4.0 version web browsers, we can even tell it should appear on the screen.

Why would we want to do this? If we are doing something like loading an image in a new web browser window, there is no real need for all of the browser buttons and fields, which take up valuable screen real estate. Furthermore, it allows us to create small web browser windows that can work like "tool palettes" in other computer programs.

The general JavaScript approach to writing this code looks like:

  <A HREF="#dummy_anchor" onClick="window.open('URL', 'window_name', 'window_options')">linking text</a>

As we saw in lesson 27 we replace the URL in the href attribute with a link to some named anchor within this document. We must do this because the browser will want to jump to some location; this method keeps us in the same page. Typically, we place this anchor just above the HTML that contains this JavaScript because the browser will scroll to the location of this "dummy anchor".

The onClick JavaScript event initiates the action; a command called window.open() that talks to the web browser and tells it to open a new window. The window is filled with the content specified by the URL in the first parameter, which in the above examples was an image file, but could also be a local HTML file or a remote URL. The second parameter provides a "name" for this window, in case we use it again to target a link (see lesson 25).

The third parameter is where we list all the options that indicate how the window will appear. These items are all in one string of text enclosed in quotes:

  1. toolbar
    displays the browser buttons (forward, back, home, print, etc)
  2. location
    displays the field that shows the URL for the window
  3. directories
    displays other web browser directory buttons
  4. status
    displays the browser status bar at the bottom
  5. menubar
    displays the web browser menu bar
  6. resizable
    allows user to change the size of the window
  7. scrollbars
    provides scroll bars if the content is larger than the window size
  8. width=XX
    specifies the width of the window when opened, in pixels
  9. height=YY
    specifies the height of the window when opened, in pixels

You can list the first seven as OPTION=yes or OPTION=no to indicate that we want them to be used or not used in our newly opened window, separating each by a comma. For example:

I have provided a sneak peek of <A HREF="#a" onClick="window.open('myimage.gif', 'myWin', 'toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=no, scrollbars=no, width=300, height=200')">my image</a> for you to see.

will create a link to open an image file myimage.gif in window named "myWin", that shows no browser buttons, and is pretty much a fixed window size; you cannot resize it or scroll it.

On the other hand, we could link to a URL in a new window:

How about trying the best <A HREF="#a" onClick="window.open('http://www.mcli.dist.maricopa.edu/tut/', 'myWin', 'toolbar=yes, directories=no, location=no, status=yes, menubar=no, resizable=yes, scrollbars=yes, width=500, height=400')">web page tutorial in the universe</a> for free!

This code provides the browser navigation buttons (but not the extra directory ones) and the URL display field. The window is opened at a window that is 500 pixels wide and 400 pixels high, and we allow the viewer to resize it and the window will have scrollbars activated.

You can write these options more compactly by just listing the ones that you wish to activate; the browser assumes the ones not mentioned are turned "off". For examples, here is the alternative way to write the two examples above:

I have provided a sneak peek of <A HREF="#a" onClick="window.open('myimage.gif', 'myWin', 'status, width=300, height=200')">my image</a> for you to see.

How about trying the best <A HREF="#a" onClick="window.open('http://www.mcli.dist.maricopa.edu/tut/', 'myWin', 'toolbar,status,resizable,scrollbars,width=500,height=400')"> web page tutorial in the universe</a> for free!

With the 4.0 versions (and later) of NetScape and Internet Explorer browsers, we can also, through JavaScript, specify the location on the screen that the window opens. These dimensions are given in pixels, measured horizontally and vertically down from the top left corner of the screen. Older web browsers will just ignore these options.

Unfortunately, NetScape and Internet Explorer use different names for these options! So to make it work on both browsers, you must specify the settings twice:

  1. screenX=hh,screenY=yy
    specifies the location of the upper left corner of the window, measured from the top left corner of the monitor (for NetScape 4.0 and later)
  2. left=hh,top=yy
    specifies the location of the upper left corner of the window, measured from the top left corner of the monitor (for Internet Explorer 4.0 and later)

Adding on to our earlier example, This code will tell 4.0 version web browsers to place the window 100 pixels over and 75 pixels down from the top left corner of the viewer's screen:

I have provided a sneak peek of <A HREF="#a" onClick="window.open('myimage.gif', 'myWin', 'toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=no, scrollbars=no, width=300, height=200, screenX=100,screenY=75,left=100,top=75')">my image</a> for you to see.

Putting it in Your <HEAD>

previous: "Framed Web Sites" | next: "Adding some FORM to your webs" |