Chapter 15
Script Example 1: Hello World
In This Chapter
Putting It All Together
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.
|
If you've made it this far, you probably wonder when the background information, command lists, statement explanations, and other groundwork will stop and the real fun begin: creating your own real JavaScript Web pages. Wait no longer-the fun starts now! Since 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'll use for the rest of the examples in this book.
The Basic Template
You can use the following template as a framework for all 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 the only way to script--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 mentioned in Chapter 4, 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
You want to present a simple page and, when the user clicks a button, display a JavaScript dialog with the phrase "Hello World from the Land of JavaScript!" If you remember back a bit, this is accomplished 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!")
}
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 by choosing, under the File menu, an option named something such as "Open file" or "Open local file."
|
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>
When you fire up Netscape Navigator and run this script, you should get something like what you see in the next figure.
A couple of things to note. 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 to forget 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, which will yield the exact same results as the earlier example:
<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 that elaborate-you have to start somewhere! Take a little deviation from your template 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.
Remember from Chapter 13 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 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. Take 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
Now, 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 user interaction. In the HTML version, the message is plopped onto the screen and it's there for good. Thus, JavaScript allows you to generate on-screen messages via HTML code in reaction
to conditions or user events.
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 that 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)
{
recipes="<A HREF=" + spice + ".html>See recipes using " + spice + "</A><p>";
trading="<A HREF=" + spice + "trade.html>See history of " + 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>
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 create a form in which there are two button elements. 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 purposes, that the document containing garlic recipes will be called "garlic.html," 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. Within JavaScript's mind, the following string winds up being assigned to recipes:
"<A HREF=garlic.html>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 this HTML to the browser window, as seen 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.
Since Netscape Navigator 2.0 is the only browser that can handle JavaScript right now, it's a nice touch to make it possible for visitors who don't use this browser to still view your pages_even if it is in a reduced 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 2.0</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.html">Click here</A>.')
//->
</SCRIPT>
</BODY>
</HTML>
The following figure shows the result. 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'll see on-screen.
Only a JavaScript-enabled browser will display the last line.
|
|
The Least You Need To Know
Clarify Your Marks
|
Note that when you have to use double quotes for something else in the display line (such as a URL), you can use single quotes to bracket the entire display string. Or you can use double quotes to bracket the entire string, and single quotes within it. Either way works, as long as you are consistent; if you start the string with a double quote, be sure to bracket the end of the string with a double quote and use single quotes when necessary within. And vice versa.
|
Now that you've seen all that makes up JavaScript, you embarked 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.



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.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.