Chapter 18
Script Example 1: Hello World

In This Chapter

Putting It All Together

If you've made it this far, you’ve probably been wondering when the background information, command lists, statement explanations, and other groundwork would stop and the real fun—creating your own real JavaScript Web pages—would begin. Wait no longer! The fun starts now! Because no introduction to a new computer language would be complete without the requisite "Hello World" application, that's where you'll start. Your little "Hello World" script will also give you a basic HTML framework that you can use for the rest of the examples in this book.

[ic:check]Hello World? Every discipline has its traditions, and programming is no exception. One
long-standing ritual found in almost every introductory book on any computer programming language 
is to have the first program be one that displays the phrase "Hello World" on the screen.

The Basic Template

You can use the following template as a framework for all of your JavaScript files. From time to time, you may want to move things around a bit, but that's what templates are for: to give you a starting point. Don't consider them to be the only way to script—they’re just one possibility.

<HTML>
<HEAD>
<TITLE>Your Title Here</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from non-JavaScript browsers
// your script statements go here
//-->
</SCRIPT>
</HEAD>
<BODY>
// Your HTML display statements go here
</BODY>
</HTML>

As I mentioned in Chapter 3, the <SCRIPT> tag serves as a wrapper around JavaScript statements, and you can place it anywhere within the HTML file. For the sake of consistency, place it in the <HEAD> tag.

Hello World 1

Suppose you want to present a simple page that displays a JavaScript dialog with the phrase "Hello World from the Land of JavaScript!" when the user clicks a button. If you remember back a bit, you can accomplish this through the use of an event handler that runs a function. The event handler you need to use is onClick, and the function is a simple one:

function HelloWorld()
{
alert("Hello World from the Land of JavaScript!")
}
So, putting it together, you get:
<HTML>
<TITLE>Hello World</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from non-JavaScript browsers
function HelloWorld()
{
alert("Hello World from the Land of JavaScript!")
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Click on the button below to receive a _special message:
<P>
<INPUT TYPE="submit" VALUE="Click Me!" _ONCLICK="HelloWorld()"> 
</FORM>
</BODY>
</HTML>

[ic:check]Run Script, Run

"Running" a JavaScript program is as simple as loading the HTML document into the Web browser.
If you've created the script file on the same computer on which the browser is installed, you will load a
"local file." Do this opening the File menu and choosing an option named something like Open file or
Open local file.

When you fire up Netscape Navigator and run this script, you should get something like what you see in the next figure.

Hello World!

There are a couple of things to note here. First, the JavaScript code for buttons needs to go inside a <FORM> tag; otherwise, it's simply ignored (you can test this by removing the <FORM> tag from the above script and running it again). One of the most common mistakes beginning Web writers make is forgetting to use the <FORM> tag; and then they wonder why their buttons and check boxes aren't being displayed.

Note that, in the previous example, you're using a Submit button (as defined by the <INPUT> tag attribute TYPE="submit"). The Submit button also generates an onSubmit event, which you could have used to equal effectiveness as the onClick event in this case. However, the onSubmit event handler is defined in the <FORM> tag not the <INPUT> tag. You can check this out for yourself by replacing the previous example with the following one, which will yield the exact same results:

<FORM ONSUBMIT="HelloWorld()"><INPUT TYPE="submit" VALUE="Click Me!"> </FORM> 

Congratulations, you're now a JavaScripter!

Hello World 2

Okay, so your first little example wasn't all that elaborate. Well, you have to start somewhere! Now you’re ready to deviate from your template a little and look at a more significantly useful way to place text on the screen. Now you will generate new messages directly into the on-screen document.

You may remember (from Chapter 12) that one of the objects JavaScript gives you is the document object, which provides a way to program the currently displayed document. Normally, when you load a Web page, the HTML statements within it are interpreted and displayed by the browser. With JavaScript, you can write HTML statements directly into the document at any time, as generated on-the-fly by your JavaScript program. To see what I mean, consider the following example:

<HTML>
<TITLE>Hello World</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from non-JavaScript browsers
document.write("<H2>Hello World from the Land of JavaScript!</H2>")
//-->
</SCRIPT>
</HEAD>
<BODY>
<P>

(the previous message compliments of JavaScript)

</BODY>
</HTML>

Running this document produces the same output as the following non-JavaScript page:

<HTML>
<TITLE>Hello World</TITLE>
<HEAD>
<H2>Hello World from the Land of JavaScript!</H2>
</HEAD>
<BODY>
<P>

(the previous message compliments of JavaScript)

</BODY>
</HTML>

Interactive Style

Given the previous two examples, you might be thinking, "So what was the point of that?" Consider, though, that in the JavaScript version, you could have output that message at any time as a result of certain conditions having been met or a certain type of user interaction. In the HTML version, the message is plopped onto the screen, and it's there for good. Thus, JavaScript enables you to generate on-screen messages via HTML code in reaction to conditions or user events.

A New Spin

Now let’s rework the first example so that you wind up with something truly JavaScripty. The following program will be a mini "tour guide" front-end to a display on the history of spices. Two buttons will appear in the window, each containing the name of a spice. When the user chooses the spice, a JavaScript function is called that generates new HTML code on-the-fly for display on the screen. This new code will display two appropriately phrased links that lead toward new (hypothetical) documents: one containing recipes that use the spice, and the other containing a history of trade for that spice. This sounds complicated, but it is, in fact, simple with JavaScript.

<HTML>
<TITLE>Spice Tours 96</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--Hide script from non-JavaScript browsers
function tour(spice)
{
var recipes="<A HREF=" + spice + ".htm>See recipes using " + spice + "</A><p>";
var trading="<A HREF=" + spice + "trade.htm>See history of the " + spice + " trade</A><p>" ;
document.write("<H2>Please select one of the guided tours below<H2>") ;
document.write(recipes) ;
document.write(trading) }
//-->
</SCRIPT>
</HEAD>
<BODY>

Please click on the desired spice below:

<FORM>
<INPUT TYPE="button" VALUE="Garlic" ONCLICK="tour('garlic')">
<INPUT TYPE="button" VALUE="Cinnamon" ONCLICK="tour('cinnamon')">
</FORM>
</BODY>
</HTML>

The following two figures illustrate what the user would see when interacting with the this program.

Here, the salivating user can select which spice to learn more about.

After the user has selected a spice trail to follow, the JavaScript program generates some new HTML code on-the-fly, reflecting the user’s choice and displaying a suitable page. As pictured here, the new page refers to the spice the user has chosen. As well, the hyperlinks lead to pages specific to the chosen spice.

The JavaScript function then generates new HTML code to display the above spice-appropriate hyperlinks.

Let's consider the previous program. It basically contains two segments. The JavaScript function definition comes first, and the HTML code defining the button options comes second. First consider the HTML code. It should look familiar by now: You created a form in which there are two button elements, and you labeled each button with a spice name. You could have coded as many buttons as you wanted. Both buttons contain an onClick event handler, calling the function tour(). Notice how you pass a string literal, representing the spice in question, as the parameter to tour().

Now consider the tour() function. The first line of statements, an assignment to the variable recipes, looks complicated but is actually simple. The purpose of this line is to paste together a string containing the full HTML code for a hyperlink. It then assigns that whole string to the variable recipes. You can assume, for example, that the document containing garlic recipes will be called "garlic.htm," and so you use a combination of concatenations to construct this string. Recall that the variable spice contains either the string "garlic" or “cinnamon,” depending on which button the user clicked. Therefore, according to JavaScript, the following string winds up being assigned to recipes:

"<A HREF=garlic.htm>See recipes using garlic</A><p>"

This is HTML for a hyperlink and will momentarily be output to the browser window.

The second statement line constructs a similar link for the history of trading. This is followed by three document.write() statements, which simply output all of this HTML to the browser window, as shown in the previous figure.

Web Etiquette

If you've done a bit of Web surfing, no doubt you've encountered many pages that have links "for text-based browsers" or "for non-Netscape browsers." Because there are several "standards" on the Web today, not all browsers can handle all things. Thoughtful Web authors try to accommodate this by creating different collections of pages that are tailored to different types of browsers.

Although the most popular browsers (Netscape Navigator 2.0 or greater and Internet Explorer 3.0 or greater) support JavaScript, some other browsers are still in use out there . For those who do not use JavaScript-capable browsers, it's nice to still be able to view your pages, even if the pages’ features and functionality are reduced in some way. You can do this quite neatly by taking advantage of what you just learned.

Because you can generate HTML using the document.write() method, you can create the following JavaScript-aware page:

<HTML>
<TITLE>Welcome to My JavaScript</TITLE>
<BODY>
<H1>So...you're interested in JavaScript?</H1>

Hello World! Well, you've come to the right place for JavaScript.

But, if you don't have <A HREF="http://home.netscape.com/">Netscape

Navigator</A> or <A HREF=”http://www.microsoft.com/ie/default.asp”>Microsoft Internet Explorer</A>, you won't be able to see any of the fun!

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from non-JavaScript browsers
document.write("<HR>")
document.write("<P>")
document.write("To proceed to my JavaScript pages,")
document.write('<A HREF="myjavascript.htm">Click here</A>.')
//-->
</SCRIPT>
</BODY>
</HTML>

The following figure shows the resulting page. With this little trick, you can keep people from trying to view your JavaScript pages if they don't have a browser that can handle it. That way, they won't be disappointed by the gibberish they see on-screen.

Only a JavaScript-enabled browser will display the last line.

The Least You Need to Know

Having seen all that makes up JavaScript in the earlier chapters of this book, you now embark on the adventure of creating your own pages. In your first example, you displayed a simple "Hello World" message in two ways: from within the document through the document object and from the JavaScript alert() function. You then constructed a user-interactive program that generated context-appropriate messages on-screen. Finally, you saw that you can hide URL links inside a script to keep non-JavaScript browsers from displaying things that wouldn't work for them.

Clarify Your Marks

Note that when you have to use double quotation marks for something else in the display line 
(such as an URL), you can use single quotation marks to bracket the entire display string. Or you can use 
double quotation marks to bracket the entire string and single quotation marks within it. Either way works, 
as long as you are consistent: If you start the string with a double quotation mark, be sure to bracket the end
of the string with a double quotation mark and use single quotation marks when necessary w
ithin. (And vice versa.)

Previous Chapter Next Chapter


Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.