Three simple JavaScripts that add
spice to your Web pages
By Jim Heid
Want to perk up your Web pages?
Try a spot of JavaScript to enhance your pages' interactivity and make them
easier to navigate. JavaScript's name implies it's a simple, easy-to-learn
scripting language. The truth is that JavaScript is a full-fledged programming
language that requires considerable programming skills to master fully.
But that doesn't mean it isn't useful to the rest of us--far from it.
There are innumerable ways to spice up a Web page with JavaScripts, and there are
just as many sources for canned scripts that you can apply to your pages with
just a few easy modifications.
This month, I present three JavaScript tricks for you to try. Ranging
from extremely simple to fairly complex, they illustrate how JavaScript can
enhance a Web site's user interface to make it more dynamic and CD-ROM-like.
Because JavaScript isn't fun to type--and because, as with any
programming language, typos equal failure--the longer scripts aren't printed
here. To get the complete scripts and for links to more JavaScript information
sources, visit www.heidsite.com.
Where the Scripts Live
All of the scripts I present here are
client-side scripts: They execute on a computer that is running a
JavaScript-capable Web browser. When the browser reads a page containing a
script, a JavaScript interpreter swings into action and executes the script.
Generally, client-side JavaScripts live directly within an HTML page. I
say "generally" because it's possible to store a script in a separate file and
then call it from an HTML page. This is a useful technique if you want to run the
same large script on multiple pages.
What about that phrase JavaScript-capable browser? There are just two,
but they are the top two browsers: Netscape Navigator and Microsoft Internet
Explorer. JavaScript debuted in Navigator 2.0, and Netscape has enhanced it for
each Navigator release.
For Internet Explorer 3.0, Microsoft developed its own implementation of
JavaScript, called JScript. The two are very similar, although there are enough
incompatibilities to make life difficult for advanced scripters. (Would you
expect anything else from the Microsoft-Netscape rivalry?) Of the scripts
presented here, all but one, Rollover Graphic Buttons, work on both Navigator and
Internet Explorer 3.0 and later versions, on both the Mac and Windows. The
button-rollover script doesn't work on Internet Explorer, but it doesn't cause
any problems or error messages.
In your travels with JavaScript, you'll sometimes see scripts enclosed
within the <script> and </script> tags; at other times you'll see scripts
used as attributes for existing HTML tags. Scripts can reside in different places
within an HTML page. Generally, scripts used as attributes for HTML tags perform
a simple task that relates to the tag itself--for example, adding a message to
the status bar when the mouse pointer is over a hyperlink. Scripts sandwiched
between <script> and </script> are typically more complex and often define
tasks that are called elsewhere in the page--for example, swapping one graphic
with another when the mouse pointer moves over a link graphic.
Using the Canned Scripts
With the appetizer out of the way,
now let's move on to the main course. Each of the scripts included in this
article (plus one bonus script for creating a remote-control navigation window)
is available at www.heidsite.com. Each contains comments on how to modify the
script for your pages.
These comments don't describe in detail how the scripts work. (I myself am not
a JavaScript programmer--the scripts here are ones that I've picked up from books
and JavaScript resource sites. I've listed several good sources in "Where to
Learn More about JavaScript.") But that's the beauty of JavaScript. We
nonprogrammers can work with it on a simple level to perk up our pages. At the
same time, programmers can use JavaScript to accomplish sophisticated tasks:
checking and calculating information entered into a form; tracking a user's
progress through a site with browser cookies; and handling a shopping cart that
enables visitors to shop until their browsers drop.
One thing JavaScript can't do is prevent a writer from ending a
JavaScript column with a coffee pun. That takes willpower, strength of character,
and a burning desire to stick to the ...script.
My Final Column
My first Macworld column appeared in the
March 1985 issue--153 consecutive columns and nearly 400,000 words ago. This, I'm
sad to say, is my final column. Macworld and the Mac world are undergoing
numerous changes these days, and the Media column as we know it today is one
casualty of this evolution. But look for my work elsewhere in future pages of
Macworld.
It has been a genuine pleasure to appear here each month. I have learned
something new with every column; if you did, too, then I've done my job. Thanks
for reading.
_______________________________
JIM HEID's HTML & Web
Publishing Secrets (IDG Books Worldwide, 1997) contains dozens of canned
JavaScripts and not a single coffee pun.
_______________________________
Sidebar
Where to Learn More about JavaScript
The Web itself is a terrific JavaScript resource. Take a look at Gamelan
(www.gamelan.com) and JavaScript Tip of the Week (www.webreference.com/javascript/).
The latter is no longer being updated, but its archive offers more than 30 tips.
The best JavaScript book I've found is JavaScript: The Definitive
Guide, second edition, by David Flanagan (O'Reilly & Associates, 1997). A
great cookbook is Designing with JavaScript, by Nick Heinle (O'Reilly
& Associates, 1997).
_______________________________
Sidebar
Fun with Status Bars
JavaScript lets you control the contents
of the browser's status bar, that area at the bottom of the browser window where
URLs and download-status information appear. You can take advantage of this to
provide feedback and information.
Default Messages
With the JavaScript defaultStatus property, you can specify a message
that appears in the status bar as long as that page is visible. When visitors
move the mouse pointer over a link, the link's URL replaces the message. But when
they move the pointer off a link, the default message reappears. You might use
this script to provide help for beginners ("Click on the underlined text to go to
other pages") or to give a brief description of a page ("Subscribe to our e-mail
newsletter here").
This script displays a message in the browser's status bar.
<script>
defaultStatus = "Welcome to the Acme
Corporation Web site."
</script>
Rollover Messages
A slightly more complex variation on the theme
involves displaying a different status-bar message for each link on a page. When
the pointer moves over a link, a message rather than a URL appears in the status
bar. Use this feature to provide a brief description of the link ("About our
products" or "Check out our Web cam").
This rollover status-bar trick works not only with hypertext links but
also with the links in client-side image maps (discussed in Media, July 1996).
In order to have a message appear when the mouse pointer is over a link
or within an image-map hot spot, you should place this tag within the link. Type
your message between the single quotes in the onMouseOver statement. The
onMouseOut statement clears the status bar when the pointer leaves the link.
<a href="products.html"
onMouseOver = "status='Learn about our
products'; return true;"
onMouseOut = "status=";">
Products</a>
Rollover Graphic Buttons
Eyecatching buttons that change color or shape
when the mouse pointer moves over them are one of my favorite JavaScript tricks.
So-called rollover buttons have a dynamic, CD-ROM-style appearance.
A somewhat lengthy script, excerpted here, enables you to create
rollover buttons. You can download the entire script from www.heidsite.com.
Alas, this script doesn't work in Microsoft Internet Explorer. It does
work in Netscape Navigator 3.X and 4.0, though, and it doesn't cause error
messages in Explorer.
Before using this script, you must create two graphics for each button:
One graphic contains the button in its normal form, and the other contains it in
its rollover form. Both must be the same size.
TIP: This script pairs up nicely with the status-bar message script.
When visitors move the pointer over a button, the button changes shape and a
status-bar message appears. Dynamic enough for you?
<a href="intro.html"
onMouseOver="over('introduction');
window.status='What is No Back
Roads?'; return true;"
onMouseOut="out('introduction')"><imgname='introduction'
src="gfx/introduction-o.gif" height=14 width=97 border=0></a>
A Navigation Pop-up Menu
Another popular JavaScript-based
site-navigation aid is a pop-up menu that enables visitors to jump to a specific
page. Navigation pop-ups are handy because they pack a lot of navigation power
into a small space and they're easy to use.
A No-Go Variation
While some navigation pop-up menu scripts require that a visitor click on the
Go button to confirm his or her choice, this one doesn't. Instead, it swings into
action the moment a visitor chooses a destination. In other words, the script
provided here works exactly the way a Mac OS or Windows menu does (the
www.webreference.com JavaScript Tip of the Week contains such a script).
TIP: For the Web, I prefer having to click on a Go button. It's
too easy to accidentally choose an option (or to choose the wrong option) because
your finger slipped off the mouse button--and on the Web, a mistake like that can
cost a visitor several seconds in annoyance while the browser locates and
displays the wrong page.
<html>
<head>
<title>A Web Page</title>
<script language="JavaScript">
<!--// hide
/*
Live popup menu script from "HTML & Web Publishing Secrets"
(IDG Books, 1997)
Original code is Copyright (©) 1996 Athenia Associates, all rights
reserved. By Andrew King (aking@webreference.com) of
webreference.com. Modified by Jim Heid.
To use this script, you must modify the lines below that begin "var
siteopt" and "var url."
In the line that begins "var siteopt," replace the items within quotes
(Breakfast, Lunch, Dinner, Snack) with the names of the categories or pages on
your site. You can add additional items; just make sure each one is enclosed
within quotes and that a comma separates each quoted item.
Next, modify the
line that reads "var url," replacing the HTML page names with the appropriate
URLs.
*/
function createArray() {
this.length =
createArray.arguments.length+1
for (var i = 0; i < this.length-1;
i++)
this[i+1] = createArray.arguments[i]
}
var siteopt = new createArray("Breakfast", "Lunch", "Dinner", "Snack"); var
url = new createArray("breakfast.html", "lunch.html", "dinner.html",
"snack.html");
function jumpPage(form) {
menuNum =
document.menu.primary.selectedIndex;
window.location.href = url[menuNum+1];
}
// -->
</script>
</head>
<body bgcolor="#ffffff"
text="#000000" link="#0000ff" vlink="#ff0000">
<script language =
"JavaScript">
<!--
with (document) {
write('<center><table
width=465 border=0 cellpadding=5 cellspacing=0>');
write('<form name = "menu"><tr>');
writeln('<td valign=top
colspan
=2>');
writeln('<font size = -1 face = arial>Select an
area</font><br>');
writeln('<select name="primary" onChange="jumpPage()">');
tot = siteopt.length;
for (var i = 1; i < tot; i++)
writeln("<option>" +siteopt[i]);
writeln('</select>');
write('<input type = button value = "Go!" onClick ="jumpPage()">');
write('</td></tr></form></table></center>');
}
// -->
</script>
</body>
</html>
December 1997 page: 171