Adding Interactivity - Interactivity and Multimedia - Creating a Website: The Missing Manual (2015)

Creating a Website: The Missing Manual (2015)

Part 4. Interactivity and Multimedia

Chapter 14, JavaScript: Adding Interactivity

Chapter 15, Dynamic Buttons and Menus

Chapter 16, Audio and Video

Chapter 14. JavaScript: Adding Interactivity

JavaScript is a simplified programming language designed to beef up web pages with interactive features. It gives you just enough programming muscle to add some fancy effects, but not enough to cause serious damage to your site if your code goes wonky. JavaScript is perfect for creating pop-up windows, embedding animated effects, and modifying the content on your web page. On the other hand, it can’t help you build a hot ecommerce storefront; for that, you need the PayPal tools described in Chapter 13 or a server-side programming platform (see Server-Side and Client-Side Programming).

The goal of this chapter isn’t to teach you the details of JavaScript programming—it’s to give you enough background so you can find great free JavaScript code online, understand it well enough to make basic changes, and then paste it into your pages to get the results you want.

NOTE

In fact, you’ve already used JavaScript (perhaps unwittingly) in some of the examples in this book. You used it to track visitors to your site with Google Analytics (Understanding Google Analytics), to fetch a suitable block of ads for your AdSense-enabled web page (Placing Ads in Your Web Pages), and to grab a list of your recent tweets to show on your site (Sharing Your Tweets on Your Site). In all these cases, you used a block of ready-made JavaScript code (or a reference to a ready-made JavaScript file). You got the benefits of JavaScript interactivity without needing to write a line of code yourself. Now you’ll learn how JavaScript actually works.

Understanding JavaScript

The JavaScript language has a long history; it first hit the scene with the Netscape Navigator 2 browser in 1995. Internet Explorer jumped on the bandwagon with version 3. Today, all modern browsers run JavaScript, and it’s become wildly popular as a result.

Here’s what JavaScript can do:

§ Dynamically insert new content into a web page or modify an existing HTML element. For example, you can display a personalized message to your visitors (“Hello, Joe!”) or make titles grow and shrink perpetually (see the example on Using HTML Objects in a Script).

§ Gather information about the current date, your visitor’s browser, or the text your visitor types into a form. You can display any of this information on a web page or use it to make decisions about what your page does next. For example, you could stop visitors from going any further in your site until they type in an email address.

§ React to events that take place in a browser. For example, you can add JavaScript code that runs when a page finishes loading or when a visitor clicks a picture.

§ Talk to a program running on a web server. JavaScript can poll the server for a recent stock quote, for example, or for a bunch of records from a company database. This is one task you won’t see covered in this chapter, because it requires some serious programming mojo to write the non-JavaScript code that runs on the web server.

It’s just as important to understand what JavaScript can’t do. JavaScript code is sandboxed, which means that a browser locks JavaScript-containing pages into a carefully controlled place in your guests’ computer memory, known as a sandbox. As a result, the code can’t perform any potentially risky tasks on your visitor’s computer, like sending orders to a printer, opening files, running other programs, reformatting a hard drive, and so on. This design ensures good security.

section (or in thesection), the alert box would appear earlier, while the page is still blank. The browser would then wait until you clicked OK in the box before reading the rest of the HTML page and displaying its contents.">

Figure 14-1. Because you positioned the <script> element for this page at the end of the HTML markup, the browser displays all the HTML first and then pops up the alert box. If you put the <script> element at the beginning of the <body> section (or in the <head> section), the alert box would appear earlier, while the page is still blank. The browser would then wait until you clicked OK in the box before reading the rest of the HTML page and displaying its contents.

You’re probably wondering exactly how this script works its magic. When a browser processes it, the script runs all the code, going one line at a time. In this case, there’s only one line:

alert("Welcome, JavaScript coder.")

This line uses a built-in JavaScript function called alert. A function is a piece of code that performs a certain well-defined task and that you can use over and over again. JavaScript has many built-in functions, but you can also build your own.

JavaScript’s alert() function requires one piece of information, known as an argument in programmer-speak. In this case, that piece of information is the text you want the alert box to display. If you want to see an ordinary number, say 6, you could type it in as is—that is, you don’t need to put it in quotes. But with text, there’s no way for a browser to tell where text starts and stops. To compensate for this in JavaScript, you put text inside single quotation marks (') or double quotation marks ("), as in the previous example.

NOTE

Programmers call a distinct piece of text used in a program a string. “The friendly fox,” “a,” and “Rumpelstiltskin” all qualify as strings.

That’s it. All this simple script does is call JavaScript’s alert() function. (Spend enough time around programmers and JavaScript fans, and you’ll soon learn that “call” is the preferred way to describe the action that triggers a function.) The alert() function does the rest, popping up a pre-sized window that displays an exclamation-point logo and whatever message you typed in. The box stays onscreen until your visitor clicks OK.

NOTE

To write this script, you need to know that there’s an alert() function ready for you to use—a fact you can find out on one of the many JavaScript tutorial sites.

Based on what you now know, you should be able to change this script to:

§ Display a different message (by changing the argument).

§ Display more than one message box, one after the other (by adding more lines in your <script> block).

§ Display the message box before your browser displays the web page (by changing the position of the <script> block).

It’s not much to keep you occupied, but the alert() function does show you how easily you can get started using and changing a simple script.

GEM IN THE ROUGH: DEALING WITH INTERNET EXPLORER’S PARANOIA

If you run the alert example above in the Firefox browser, you’ll find that everything works seamlessly. If you run it in Internet Explorer, you won’t get the same satisfaction. Instead, you’ll see a security warning in a yellow bar at the top of the page. Until you click that bar and then choose Allow Blocked Content, your JavaScript code won’t run.

At first glance, IE’s security warning seems like a surefire way to scare off the bravest web visitor. But you don’t need to worry; the message is just part of the quirky way Internet Explorer deals with web pages that you store on your hard drive. When you open the same page over the Web, Internet Explorer won’t raise the slightest objection.

That said, the security warning is still an annoyance while you’re testing your web page, because it forces you to keep explicitly telling the browser to allow the page to run JavaScript. To avoid the security notice altogether, you can tell Internet Explorer to pretend you downloaded your page from a web server. You do this by adding a special comment called the Mark of the Web. You place this comment immediately after the <html> element that begins your page:

<html>

<!-- saved from url=(0014)about:internet

-->

When IE sees the Mark of the Web, it treats the page as though it came from a web server, skipping the security warning and running your JavaScript code without hesitation. To all other browsers, the Mark of the Web just looks like an ordinary HTML comment.

Browsers that Don’t Support Javascript

It’s rare, but some browsers will recognize the <script> element but refuse to run your code. This can happen if a browser doesn’t support JavaScript (for example, a dusty text-only browser like Lynx) or if JavaScript has been switched off (which is possible in paranoid corporate environments, but still very rare).

To deal with the occasional situation like this, you can use the <noscript> element, which lets you supply alternate HTML content. You place the <noscript> element immediately after the closing </script> tag. Here’s an example that displays a paragraph of text for browsers that lack JavaScript support:

<script>

alert("Welcome, JavaScript coder.")

</script>

<noscript>

<p>Welcome, non-JavaScript-enabled browser.</p>

</noscript>

Variables

Every programming language includes the concept of variables, which are temporary containers that store important information. Variables can store numbers, objects, or pieces of text. As you’ll see throughout this chapter, variables play a key role in many scripts, and they’re a powerful tool in any programmer’s arsenal.

Declaring Variables

To create a variable in JavaScript, you use the var keyword, followed by the name of the variable. You can choose any name that makes sense to you, as long as you’re consistent (and avoid spaces or special characters). This example creates a variable named myMessage:

var myMessage

You’ll often want to create a variable and fill it with useful content all in the same step. To store information in a variable, you use the equal sign (=), which copies the data on the right side of the equal sign into the variable on the left. Here’s an example that puts some text into myMessage:

myMessage = "Everybody loves variables"

Remember, you need to use quotation marks whenever you include a text string. In contrast, if you want to copy a number into a variable, you don’t need quotation marks:

myNumber = 27.3

JavaScript variables are case-sensitive, which means a variable named myMessage differs from one named MyMessage. This detail seems innocent enough, but it’s the source of plenty of headaches (see the box on Phantom Variables).

Modifying Variables

One of the most useful things you can do with numeric variables is perform operations on them to change your data. For example, you can use arithmetic operators to perform mathematical calculations:

var myNumber = (10 + 5) * 2 / 5

TROUBLESHOOTING MOMENT: PHANTOM VARIABLES

To make matters a little confusing, JavaScript lets you refer to variables you haven’t yet declared. Doing so is considered extremely bad form and is likely to cause all sorts of problems. However, it’s worth knowing that these undeclared variables are permissible, because they’re the source of many an unexpected error.

For example, a common mistake is to declare a variable (say, bodyWeight) but then refer to it with a slightly different name (like bodyWght) or slightly different capitalization (like BodyWeight). In this situation, you’ve unwittingly created two variables. The usual result is a page that behaves strangely—for example, a page that performs a calculation but gets the wrong answer.

There’s no easy way to defend yourself against this sort of mistake. If you suspect you have a variable with multiple personalities, you can add undefined variable checks to your code. Essentially, this means you check whether a suspect variable has been defined before you attempt to use it. You can read more about this technique at http://tinyurl.com/undef-js.

These calculations follow the standard order of operations (parentheses first, then multiplication and division, then addition and subtraction). The result of this calculation is 6.

You can also use operations to join together multiple pieces of text into one long string. In this case, you use the plus sign (+):

var firstName = "Sarah"

var lastName = "Smithers"

var fullName = firstName + " " + lastName

Now the fullName variable holds the text “Sarah Smithers.” (The “ ” in the code above tells JavaScript to leave a space between the two names).

An Example with Variables

Although you’d need to read a thick volume to learn everything there is to know about variables, you can pick up a lot from a simple example. The following script inserts the current date into a web page. The relevant lines of code are numbered for easy reference.

<!DOCTYPE html>

<html>

<head>

<title>JavaScript Test</title>

</head>

<body>

<h1>What Day Is It?</h1>

<p>This page uses JavaScript.</p>

<p>

<script>

1 var currentDate = new Date()

2 var message = "The current date is: "

3 message = message + currentDate.toDateString()

4 document.write(message)

</script>

</p>

</body>

</html>

Here’s what’s happening, line by line:

1. This line creates a variable named currentDate.

It fills the variable with a new Date object (see number 3 below). You’ll know JavaScript is creating an object when you see the keyword new. (You’ll learn more about objects on HTML Objects; for now, it’s enough to know that they come with built-in functions that work more or less the same way as the functions you learned about earlier.)

2. This line creates a new variable named message.

It fills the variable with the beginning of a sentence that announces the date.

3. This line adds some new text to the end of the message you created in line 2.

The text comes from the currentDate object. The tricky part is understanding that the currentDate object comes with a built-in function, toDateString(), that converts the date information it gets from your computer into a piece of text suitable for display in a browser (seeFigure 14-2). Once again, this is the kind of detail you can only pick up by studying a good JavaScript reference.

4. This line uses JavaScript’s document object, which has a function named write().

The write() function displays a piece of text on a web page at the current location. The final result is a page that shows your welcome message (see Figure 14-3).

Scripts can get much more complex than this. For example, they can use loops to repeat a single action several times or make decisions using conditional logic. You’ll see examples of some of these techniques later in this chapter, but you won’t get a blow-by-blow exploration of the JavaScript language—in fact, that would require a small book of its own. If you want to learn more, check out a book like JavaScript: The Missing Manual (O’Reilly).

Some web page editors help out when you write JavaScript code. For example, Expression Web displays a drop-down menu that shows you all the functions an object provides. Although there probably isn’t enough context for you to determine how to use the date object the first time out, it’s a great way to refresh your memory later on

Figure 14-2. Some web page editors help out when you write JavaScript code. For example, Expression Web displays a drop-down menu that shows you all the functions an object provides. Although there probably isn’t enough context for you to determine how to use the date object the first time out, it’s a great way to refresh your memory later on.

The document.write() command inserts text directly into a page, wherever you position the script block. In this case, the command displays the current date

Figure 14-3. The document.write() command inserts text directly into a page, wherever you position the script block. In this case, the command displays the current date.

UP TO SPEED: SPACES AND LINE BREAKS IN JAVASCRIPT

JavaScript code is quite tolerant of extra spaces. In this chapter, most of the examples use some sort of indenting to help you see the structure of the code. But, as with HTML, you don’t absolutely have to add these spaces.

The only rule in JavaScript is that every code statement needs to be on a separate line. You can get around this limitation by using the line-termination character, which is a semicolon (;). For example, here’s how you can compress three code statements onto one line:

alert("Hi"); alert("There"); alert("Dude");

Each semicolon designates the end of a code statement. This strange convention comes from the Bizarro world of the C and Java programming languages.

If you don’t want to put more than one code statement on the same line, you don’t need the semicolons. However, they can clarify your code, and they may help you catch certain types of mistakes. Web experts almost always use semicolons, and you’ll find them in most any script that you download from the Web.

Functions

So far, you’ve seen scripts that use only a few lines of code. More realistic JavaScript scripts can run to dozens of lines, and if you’re not careful, they can grow into a grotesque tangle that leaves the rest of your page difficult to edit. To control the chaos, smart JavaScripters almost always usecustom functions.

A function is a series of code instructions you group together and give a name. In a way, functions are like miniature programs, because they can perform a series of operations. The neat thing about them is that once you create a function, you can use it over and over again.

Declaring a Function

To create a JavaScript function, start by deciding what your function should do (like display an alert message), and then choose a suitable name for it (like ShowAlertBox). As with most things in the programming world, function names can’t have any spaces or special characters.

Now you’re ready to put the ShowAlertBox <script> block in the <head> section of your page. But this <script> block looks a little different from the examples you’ve seen so far. Here’s a complete function that shows an alert box with a predefined message:

<script>

function ShowAlertBox() {

alert("I'm a function.")

}

</script>

To understand what’s going on here, it helps to break down this example and consider it piece by piece.

Every time you declare a function, you start with the word function, which tells JavaScript what you’re up to:

function

Then you add the name of your function, followed by two parentheses. You’ll use the parentheses later to send extra information to your function, as you’ll see shortly:

function ShowAlertBox()

At this point, you’ve finished declaring the function. All that remains is to add the code to the function that actually makes it work. To do this, you need the funny curly braces shown in the alert box function above. The { brace indicates the start of your function code, and the } brace indicates the end of it. You can put as many lines of code as you want in between.

One tricky part of function writing is the fact that JavaScript sets notoriously loose standards for line breaks. That means you can create an equivalent JavaScript function and put the curly braces on their own lines, like this:

<script>

function ShowAlertBox()

{

alert("I'm a function.")

}

</script>

But don’t worry—both functions work exactly the same way.

TIP

You can put as many functions as you want in a single <script> block. Just add them one after the other.

Calling a Function

Creating a function is only half the battle. On their own, functions don’t do anything. You have to call the function somewhere in your page to actually run the code. To call a function, you use the function name, followed by parentheses:

ShowAlertBox()

NOTE

Don’t leave out the parentheses after the function name. Otherwise, browsers will assume you’re trying to use a variable rather than call a function.

You can call ShowAlertBox() anywhere you’d write ordinary JavaScript code. For example, here’s a script that displays the alert message three times in a row to really hassle your visitors:

<script>

ShowAlert()

ShowAlert()

ShowAlert()

</script>

This is the same technique you used to call the alert() function earlier. The difference is that alert() is built into JavaScript, while ShowAlertBox() is something you created. Also, the alert() function requires one argument, while ShowAlertBox() doesn’t use any.

Functions that Receive Information

The ShowAlertBox() function is beautifully simple. You just call it, and it displays an alert box with the message you supplied. Most functions don’t work this easily. In many cases, you need to send specific information to a function, or take the results of a function and use them in another operation.

For example, imagine you want to display a welcome message with some standard information in it, like the current date. But you also want the flexibility to change part of the message by substituting your own witty words each time you call the function. To do so, you need a way to call a function and to supply a text string with your message in it.

To solve this problem, you can create a ShowAlertBox() function that accepts a single parameter, or piece of information. In this case, that parameter is the customized text you want displayed in the alert box. To add the parameter, you must first give it a name, say customMessage, and put it in parentheses after the function name, like so:

function ShowAlertBox(customMessage) {

...

}

NOTE

Technically, the pieces of information that a function receives (in this case, that’s customMessage) are called parameters. When you call a function that has parameters, you pass the function one value for each parameter. The value you supply is called an argument.

In other words, the same piece of information is called a parameter from the function’s point of view and an argument from the calling code’s point of view. Sometimes, you’ll hear the terms “parameter” and “argument” used interchangeably, but now you know the official difference.

There’s no limit to how many pieces of information a function can accept. You just need to separate each parameter with a comma. Here’s an example of the ShowAlertBox() function with three parameters, named messageLine1, messageLine2, and messageLine3:

function ShowAlertBox(messageLine1, messageLine2, messageLine3) {

...

}

Here’s another example that shows a finished ShowAlertBox() function. It accepts a single parameter named customMessage, and it uses that parameter to create the text it displays in the alert box:

<script>

1 function ShowAlertBox(customMessage)

2 {

3 // Get the date.

4 var currentDate = new Date()

5

6 // Build the full message.

7 var fullMessage = "** IMPORTANT BULLETIN **\n\n"

8 fullMessage += customMessage + "\n\n"

9 fullMessage += "Generated at: " + currentDate.toTimeString() + "\n"

10 fullMessage += "This message courtesy of MagicMedia Inc."

11

12 // Show the message.

13 alert(fullMessage)

14 }

</script>

Here are some notes to help you wade through the code:

§ Any line that starts with // is a comment (see lines 3 and 6). Good programmers include lots of comments to help others understand how a function works (and to help themselves remember what they did during a late-night coding binge). The browser ignores them.

§ To put line breaks into an alert box, use the code \n (lines 7, 8, and 9). Each \n is equivalent to one line break. (This rule is for message boxes only. When you want a line break in HTML, use the familiar <br /> element.)

§ To build the text for the fullMessage variable (lines 7 to 10), the code uses a shortcut in the form of the += operator. This operator automatically takes whatever’s on the right side of the equal sign and pastes it onto the end of the variable on the left side. In other words, this:

8 fullMessage += customMessage + "\n\n"

is equivalent to this longer line:

8 fullMessage = fullMessage + customMessage + "\n\n"

Using this function is easy. Just remember that when you call it, you need to supply one argument for each parameter, separating them with a comma. In the case of the ShowAlertBox() function above, you only need to supply a single value for the customMessage variable. Here’s an example:

<script>

ShowAlertBox("This web page includes JavaScript functions.")

</script>

Figure 14-4 shows the result of this script.

This message is built out of several pieces of text, one of which you supplied as an argument to the ShowAlertBox() function

Figure 14-4. This message is built out of several pieces of text, one of which you supplied as an argument to the ShowAlertBox() function.

Functions that Return Information

Parameters let you send information to a function. You can also create functions that send information back to the script that called the function in the first place. The key to doing this is the return command, which you put right at the end of your function. The return command ends the function immediately and spits out whatever information your function generates.

Of course, a sophisticated function can accept and return information. For example, here’s a function that multiplies two numbers (the numberA and numberB parameters) and returns the result to anyone who’s interested:

<script>

function MultiplyNumbers(numberA, numberB)

{

return numberA * numberB

}

</script>

Here’s how you use this function elsewhere on your web page:

<p>The product of 3202 and 23405 is

<script>

var product = MultiplyNumbers(3202, 23405)

document.write(product)

</script>

</p>

This HTML includes a single line of text, followed by a block of script code. The script calls the MultiplyNumbers() function, gets the result (the number 74942810), and stuffs it in a variable named product for later use. The code then uses the document.write() command to display the contents of the product variable on the page. The final result is a paragraph with this text:

The product of 3202 and 23405 is 74942810

To use a typical script you get from the Web, you need to copy one or more functions into your page, and they’re likely to look a lot more complex than what you’ve seen so far. However, now that you understand the basic structure of a function, you can wade through the code to get a fundamental understanding of what’s taking place (or to at least pinpoint where the action goes down).

External Script Files

Reusing scripts inside a web page is neat, but did you know that you can share scripts between individual pages and even among different websites? You simply put your script into an external file and then link to it from a web page. This procedure is similar to the way you learned to link external style sheets back in Chapter 3.

For example, imagine you perfect the ShowAlertBox() routine so that it performs a complex task exactly the way you want it to, but it requires a couple of dozen lines of code. To simplify your life and your HTML document, create a new file to store that script.

Script files are always plain text files. Usually, they have the extension .js (for JavaScript). You put all your code inside a script file, but you don’t include the <script> element. For example, you could create this JavaScript file named ShowAlert.js:

function ShowAlertBox()

{

alert("This function is in an external file.")

}

Now save the file, and put it in the same folder as your web page. In your web page, define a script block but don’t supply any code. Instead, add the src attribute and indicate the script file you want to link to:

<script src="ShowAlert.js">

</script>

When a browser comes across this script block, it requests the ShowAlert.js file and treats it as though the code were right inside the page. Here’s a complete HTML test page that uses the ShowAlert.js file. The script in the body of the page calls the ShowAlertBox() function:

<!DOCTYPE html>

<html>

<head>

<title>Show Alert</title>

<!-- Make all the functions in the ShowAlert.js file

available in this page. Notice there's no actual content here. -->

<script src="ShowAlert.js">

</script>

</head>

<body>

<!-- Test out one of the functions. -->

<script>

ShowAlertBox()

</script>

</body>

</html>

There’s no difference in the way an embedded or external script works. However, storing your scripts in separate files helps keep your website organized and makes it easy to reuse scripts across several pages. In fact, you can even link to JavaScript functions on another website—just remember that the src attribute in the <script> block needs to point to a full URL (like http://SuperScriptSite.com/ShowAlert.js) instead of just a filename. Of course, this technique is risky because the website owner might rename, move, or modify the JavaScript file. If you really want to use the code, it’s far better to copy it to your own server to avoid this problem.

NOTE

Using separate script files doesn’t improve your security one iota. Because anyone can request your script file, a savvy web visitor can figure out what scripts your page uses and take a look at them. So never include any code or secret details in a script that you don’t want the world to know about.

Dynamic HTML

JavaScript underwent a minor revolution in the late 1990s, adding support for a set of features called dynamic HTML (also shortened to DHTML). Dynamic HTML isn’t a new technology—it’s a fusion of three distinct ingredients:

§ Scripting languages like JavaScript, which let you write code.

§ The CSS (Cascading Style Sheet) standard, which lets you control the position and appearance of an HTML element.

§ The HTML document object model (or DOM), which lets you treat an HTML page as a collection of objects.

The last point is the most important. Dynamic HTML sees a web page as a collection of objects. It treats each HTML element, including images, links, and even the lowly paragraph, as a separate programming ingredient that your JavaScript code can play with. Using these objects, you can change what each element looks like, or even where your browser places them on a page.

HTML Objects

Clearly, dynamic HTML requires a whole new way of thinking about web page design. Your scripts no longer look at your web page as a static block of HTML. Instead, they see a combination of objects.

UP TO SPEED: UNDERSTANDING OBJECTS

In many programming languages, including JavaScript, everything revolves around objects. So what, exactly, is an object?

In the programming world, an object is nothing more than a convenient way to group some related features or information. For example, say you want to change the picture shown in an <img> element on a web page (which is useful if you want to write a script that flashes a series of images). In JavaScript, the easiest way to interact with an <img> element is to use the corresponding image object. In effect, the image object is a container holding all sorts of potentially useful information about what’s happening inside an <img> element (including its dimensions, its position, the name of the image file associated with it, and so on). The image object also gives you a way to manipulate the <img> element—that is, to change some or all of these details.

For example, you can use an image object to get information about the image, like this:

document.write("The tooltip says" +

image.title)

You can even change one of these details. For example, you can modify the actual image that an <img> element shows by using this code:

image.src = "newpic.jpg"

You’ll know an object’s at work by the presence of a dot (.) in your code line. The dot separates the name of the variable (the first part) from one of the built-in functions it provides (called methods), or from one of the related variables (called properties). You always put methods and properties after a period.

In the previous examples, src and title are two of the image object’s properties. In other words, the code statement image.src = “newpic.jpg” is equivalent to saying “Hey, Mr. Object named Image: I have a new picture for you. Change your src attribute to point to newpic.jpg.”

Programmers embraced objects long ago because they’re a great way to organize code conceptually (not to mention a great way to share and reuse it). You might not realize it at first, but working with the image object is actually easier than memorizing a few dozen different commands that manipulate the image itself.

Before you can manipulate an object on your web page, you need a way to uniquely identify it. Once you do, your code can find the object whenever it needs to. The best way to identify an object is with the id attribute. Add this attribute to the start tag for the element you want to manipulate and choose a unique name, as shown here:

<h1 id="PageTitle">Welcome to My Page</h1>

Once you give your element a unique ID, JavaScript can find it in your code and act on it.

JavaScript includes a handy way to locate an object: the document.getElementById() method. Basically, document is an object that represents your whole HTML document. It’s always available, and you can use it anytime you want. This document object, like any object worthy of its name, lets you take advantage of some handy properties and methods. The getElementById() method is one of the coolest: It scans a page looking for a specific HTML element.

NOTE

In the example on An Example with Variables, you saw the document object at work on a different task—displaying information on a web page. To accomplish this feat, the script used the write() method of the document object.

When you call the document.getElementById() method, you supply the ID of the HTML element you’re looking for. Here’s an example that digs up the object for an HTML element that has the ID PageTitle:

var titleObject = document.getElementById("PageTitle")

This code gets the object for the <h1> element shown earlier and stores it in a variable named titleObject. By storing the object in a variable, you can perform a series of operations on it without having to look it up more than once.

So what, exactly, can you do with HTML objects? To a certain extent, the answer depends on the type of element you’re working with. For example, if you have a hyperlink, you can change its URL. If you have an image, you can change its source. And you can apply some actions, like changing an element’s style or modifying its text, to almost any HTML element. As you’ll see, these actions are a good way to make your pages feel more dynamic—for example, you can change a page when a visitor takes an action, like clicking a link. Interactions like these make visitors feel as though they’re using an intelligent, responsive program instead of a plain, inert web page.

Here’s how you modify the text inside the just-mentioned <h1> element, for example:

titleObject.innerHTML = "This Page Is Dynamic"

If you use this code in a script, the headline text changes as soon as your browser runs the script.

This script works because it uses the property named innerHTML, which sets the content that’s nested inside an element (in this case, the <title> element). Like all properties, innerHTML is just one aspect of an HTML object you can alter. To write JavaScript code like this, you need to know what properties the language lets you play with. Obviously, some properties apply to specific HTML elements only, like the src attribute of an image. But modern browsers boast a huge catalog of DOM properties you can use with just about any HTML element. Table 14-1 lists some of the most useful.

TIP

To figure out what properties you can use with a specific HTML element, check out the reference at www.w3schools.com/jsref.

Currently, the example above works in two steps (getting the object and then manipulating it). Although this two-step maneuver is probably the clearest approach, it’s possible to combine these two steps into one line, which scripts often do. Here’s an example:

document.getElementById("PageTitle").innerHTML = "This Page Is Dynamic"

This approach is more concise but also a bit more difficult to read.

Table 14-1. Common HTML object properties.

PROPERTY

DESCRIPTION

className

Lets you retrieve or set the class attribute (see Class Selectors). In other words, this property determines what style (if any) this element uses. Of course, you need to define this style in an embedded or linked style sheet, or you’ll end up with the plain-Jane default formatting.

innerHTML

Lets you read or change the HTML inside an element. This property is insanely useful, but it has two quirks. First, you can use it on all HTML content, including text and tags. So if you want to put bold text inside a paragraph, you can set innerHTML to <b>Hi</b>. Special characters aren’t welcome—you need to replace them with the character entities described on Special Characters.

Second, when you set innerHTML, you replace all the content inside this element, including any other HTML elements. So if you set the innerHTML of a <div> element that contains several paragraphs and images, all these items disappear, to be replaced by your new content. To modify just part of a paragraph, wrap that part in a<span> element.

parentElement

Provides the HTML object for the element that contains this element. For example, if the current element is a <b> element in a paragraph, this gets the object for the <p> element. Once you have this object, you can modify the paragraph. Using this technique (and other similar techniques in dynamic HTML), you can jump from one element to another.

style

Bundles together all the CSS attributes that determine the appearance of the HTML element. Technically, the style property returns a full-fledged style object, and you need to add another dot (.) and the name of the style attribute you want to change, as in myObject.style.fontSize. You can use the style object to dictate colors, borders, fonts, and even positioning.

tagName

Provides the name of the HTML element for this object, without the angle brackets. For example, if the current object represents an <img> element, this returns the text “img.”

Using HTML Objects in a Script

The easiest way to come to grips with how HTML objects work is to look at an example. The web pages shown in Figure 14-5 include a paragraph that continuously grows and then shrinks, as your code periodically tweaks the font size.

The way this example works is interesting. First of all, you define two variables in the <head> section of your HTML. The size variable keeps track of the current size of the text (which starts out at 10 pixels). The growIncrement variable determines how much the text size changes each time your browser runs the code (initially, it grows by 2 pixels at a time):

<!DOCTYPE html>

<html>

<head>

<title>Dynamic HTML</title>

<script>

// The current font size.

var size = 10

// The amount the font size is changing.

var growIncrement = 2

If you were looking at this heading in a live web browser, you’d see that the text is always changing size, making it difficult to ignore

Figure 14-5. If you were looking at this heading in a live web browser, you’d see that the text is always changing size, making it difficult to ignore.

Next, the script defines a function named ChangeFont(). This function retrieves the HTML object, here the <p> element holding the text that will grow and shrink. Once again, the getElementById() function does the job:

function ChangeFont() {

// Find object that represents the paragraph

// whose text size you want to change.

var paragraph = document.getElementById("animatedParagraph")

Now, using the size and growIncrement variables, you define a variable that performs a calculation to determine the new size for the paragraph:

size = size + growIncrement

In this example, the + performs a numeric addition, because both the size and growIncrement variables store a number.

It’s just as easy to set the new size using the paragraph.style.fontSize property. Just tack the letters px on the end to indicate that your style setting is measured in pixels:

paragraph.style.fontSize = size + "px"

If this code runs perpetually, you’ll eventually end up with text so ridiculously huge you can’t see any of it on the page. To prevent this from happening, you add a safety valve to the code.

Say you decide that, when the text size hits 100 pixels, you want to stop enlarging it and start shrinking it. To do this, you write the script so that it sets the growIncrement variable to −2 when the text size reaches 100. The text starts shrinking from that point on, two pixels at a time. To detect when the message has grown too big, you use conditional logic courtesy of the if statement. Here’s what it looks like:

// Decide whether to reverse direction from

// growing to shrinking (or vice versa).

if (size > 100) {

paragraph.innerHTML = "This Text is Shrinking"

growIncrement = -2

}

Of course, you don’t want the shrinking to go on forever, either. So it makes sense to add a check that determines whether the text has shrunk to 10 pixels or less, in which case the script goes back to enlarging the text by setting growIncrement back to 2:

if (size < 10) {

paragraph.innerHTML = "This Text is Growing"

growIncrement = 2

}

Now, here comes the really crafty bit. JavaScript includes a setTimeout() function that lets you instruct a browser to “call this function, but wait a bit before you do.” In this example, the setTimeout() function instructs the browser to call the ChangeFont() method again in 100 milliseconds (one-tenth of a second):

setTimeout("ChangeFont()", 100)

}

</script>

</head>

Because the ChangeFont() function always uses setTimeout() to call itself again, the shrinking and growing never stop. However, you can alter this behavior. You could, for example, add conditional logic so that JavaScript calls the setTimeout() method only a certain number of times.

The last detail is the <body> section, which contains the actual paragraph that you resize and a script that calls ChangeFont() for the first time, starting off the whole process:

<body>

<p id="animatedParagraph">This Text is Growing</p>

<script>

ChangeFont()

</script>

</body>

</html>

Although the resizing-paragraph example is absurdly impractical, the technique it uses is the basis for many much more impressive scripts. (To get the whole script and play around with it, download it from the companion site at http://prosetech.com/web.) For example, you can easily find scripts that animate text in various ways, like making it sparkle, fly in from the side of the page, or appear one letter at a time, typewriter-style.

Events

The most exciting JavaScript-powered pages are dynamic, which means they perform various actions as your visitor interacts with them (moving his mouse, typing in text, clicking things, and so on). A dynamic page is far more exciting than an ordinary HTML page, which appears in a browser and then sits there, immobile.

To create dynamic pages, you program them to react to JavaScript events. Events are notifications that an HTML element sends out when specific things happen.

For example, JavaScript gives every <a> hyperlink element an event named onmouseover (a compressed version of “on mouse-over”). As the name suggests, this event takes place (or fires, to use programmer-speak) when a visitor points to an HTML element like a paragraph, link, image, table cell, or text box. That action triggers the onmouseover event, and your code flies into action.

Here’s an example that displays an alert message when a visitor points to a link:

<!DOCTYPE html>

<html>

<head>

<title>JavaScript Test</title>

</head>

<body>

<h1>You Will Be Wowed (Again)</h1>

<p>When you hover over <a href="SomePage.htm"

onmouseover="alert('Colorless green ideas sleep furiously.')">this link</a>

you'll see a secret message.

</p>

</body>

</html>

When you write the code that makes a page react to an event, you don’t absolutely need a script block (although it’s a good idea to use one anyway, as shown in the next section). Instead, you can just put your code between quotation marks next to the event attribute:

<a onmouseover="[Code goes here]">...</a>

Notice that, in this example, the text value (‘Colorless green…’) uses single quotation marks instead of double quotes. That’s because the event attribute itself uses double quotes, and simultaneously using double quotes for two different purposes will horribly confuse your browser.

Figure 14-6 shows the result of running this script and pointing to the link.

In this example, the alert box doesn’t pop up until you point to the link

Figure 14-6. In this example, the alert box doesn’t pop up until you point to the link.

To use events effectively, you need to know what events each HTML element triggers. For example, almost any element can trigger an onClick event when it’s clicked, but it takes a text box or a list box to notify you about changes with the onChange event. Table 14-2 provides a list of commonly used JavaScript events and the HTML elements they apply to (and you can find a more complete reference at www.w3schools.com/jsref).

In the following sections, you’ll learn about two common scenarios that use some of these events.

Table 14-2. Common HTML object events.

EVENT NAME (WITH UPPERCASE LETTERS)

DESCRIPTION

APPLIES TO THESE HTML ELEMENTS

onClick

Triggered when you click an element.

Almost all

onMouseOver

Triggered when you point to an element.

Almost all

onMouseOut

Triggered when you move your mouse away from an element.

Almost all

onKeyDown

Triggered when you press a key.

<select>, <input>, <textarea>, <a>, <button>

onKeyUp

Triggered when you release a pressed key.

<select>, <input>, <textarea>, <a>, <button>

onFocus

Triggered when a control receives focus (in other words, when you position your cursor in the control so you can type something in). Controls include text boxes, checkboxes, and so on—see A Basic Form to learn more.

<select>, <input>, <textarea>, <a>, <button>

onBlur

Triggered when focus leaves a control.

<select>, <input>, <textarea>, <a>, <button>

onChange

Triggered when you change a value in an input control. In a text box, this event doesn’t fire until you move to another control.

<select>, <input type="text">, <textarea>

onSelect

Triggered when you select a portion of text in an input control.

<input type=“text”>, <textarea>

onError

Triggered when your browser fails to download an image (usually due to an incorrect URL).

<img>

onLoad

Triggered when your browser finishes downloading a new page or finishes loading an object, like an image.

<img>, <body>

onUnload

Triggered when a browser closes (“unloads”) a page. (This typically happens after you enter a new URL or when you click a link. It fires just before the browser downloads the new page.)

<body>

Image Rollovers

One of the most popular mouse events is the image rollover. To write one, you start by creating an <img> element that displays a picture. Then, when a visitor points to the image, her browser displays a new picture, thanks to the onmouseover event. Creating an image rollover is fairly easy. All you do is get the HTML object for the <img> element and then modify the src property.

But you can’t do that with a single line of code. While you could pile your entire script into the event attribute (using semicolons to separate each line), the markup would look confusing. A better choice is to write the code as a function. You can then hook the element up to the function using the event attribute.

Here’s the function that swaps an image, for example. In this script, the function is written in a very generic way using parameters, so you can use it over and over, as you’ll see in a moment. Every time you call the function, you indicate which image you want to change (by supplying the corresponding ID) and what new image you want to use. Because the function uses parameters, you can use it anywhere on your page.

<script>

function ChangeImage(imageName, newImageFile) {

// Find the object that represents the img element.

var image = document.getElementById(imageName)

// Change the picture.

image.src = newImageFile

}

</script>

When you create an image rollover, you use two events. The onmouseover event switches to the rollover picture, and the onmouseout event (triggered when your visitor moves her mouse off the HTML element) switches back to the original picture. Figure 14-7 shows the result.

<img id="SwappableImage" src="ClickMe.gif" alt=""

onmouseover="ChangeImage('SwappableImage', 'LostInterestMessage.gif')"

onmouseout="ChangeImage('SwappableImage', 'ClickMe.gif')" />

To add more rollover images, just add a new <img> element with a different name. The following element uses the same initial image (ClickMe.gif) but shows a different rollover image (PleasePleaseMessage.gif) when a visitor points to the image:

<img id="SwappableImage2" src="ClickMe.gif" alt=""

onmouseover="ChangeImage('SwappableImage2', 'PleasePleaseMessage.gif')"

onmouseout="ChangeImage('SwappableImage2', 'ClickMe.gif')" />

If you want to get really fancy, you can even use the onclick event (which guests trigger when they click an element) to throw yet another picture into the mix.

A rollover image in action

Figure 14-7. A rollover image in action.

NOTE

In Chapter 15, you’ll see a different way to approach image rollovers—using CSS. Although the CSS technique doesn’t work in every situation, it’s a great tool for building basic rollover buttons.

Collapsible Text

Another nifty way to use events is to create collapsible pages. The basic idea behind a collapsible page is this: If you’ve got a lot of information to show your visitors but don’t want to overload them with a lengthy page, you hide (or collapse) chunks of text behind headlines that guests can click to see the details (see Figure 14-8).

Dynamic HTML gives you many ways to trick browsers into hiding text, and the next example shows one of the best. The technique involves the CSS display property. When you set this property to block, an item appears in the HTML page in the normal way. But when you set it tonone, the element disappears, along with everything inside it.

Initially, the browser hides all the body text (top), but when you click the down-arrow image, it displays the content for that section (bottom). You can reveal as many sections at a time as you want

Figure 14-8. Initially, the browser hides all the body text (top), but when you click the down-arrow image, it displays the content for that section (bottom). You can reveal as many sections at a time as you want.

Your first task in building a collapsible page is creating the function that hides and then shows your content. The function requires two parameters: the name of the open/close arrow image and the name of the element you want to hide or show. The function actually does double-duty: It checks the current state of the section, and then it changes that state. In other words, it automatically shows a hidden section and automatically hides a displayed section, thanks to conditional logic. And while the function’s doing that, it swaps the open/close image to display a different type of arrow.

NOTE

The practice where you reverse the current state of an item is called toggling by jargon-happy programmers.

<script>

function ToggleVisibility(image, element){

// Find the image.

var image = document.getElementById(image)

// Find the element to hide/unhide.

var element = document.getElementById(element)

// Check the element's current state.

if (element.style.display == "none"){

// If hidden, unhide it.

element.style.display = "block"

image.src = "open.png"

}

else

{

// If not hidden, hide it.

element.style.display = "none"

image.src = "closed.png"

}

}

</script>

The code starts out by looking up the two objects you need (the arrow and the text block) and storing them in the variables image and element. Then it gets to work. It looks at the current state of the paragraph and makes a decision (using an if statement) about whether it needs to show or hide the text. Only one part of this conditional code runs. For example, if a browser is currently hiding the image (that is, if you set the display style to none), the function runs just these two lines of code, skips to the bottom of the function, and then ends:

element.style.display = "block"

image.src = "open.png"

On the other hand, if the browser is displaying the image, this code gets a chance to prove itself:

element.style.display = "none"

image.src = "closed.png"

To use this function, you need to add the <img> element that guests click to see or hide the text, along with the HTML element that contains the text. You can show or hide virtually any HTML element, but a good all-purpose choice is a <div> element because you can stuff whatever you want to hide inside it. Here’s an example:

<p>

<img id="Question1Image" src="closed.png" alt=""

onclick="ToggleVisibility('Question1Image','HiddenAnswer1')" />

<b>Where has all the information gone?</b>

</p>

<div id="HiddenAnswer1">

<p>Now you've found it. We've decided to hide parts of the

page in these neat little collapsible sections. That way you won't

see everything at once, panic, and do something drastic.</p>

</div>

The first part of the markup, between the first set of <p> tags, defines the question heading, which visitors always see. It contains the arrow image and the question (in bold). The second part (in the <div> element) is the answer, which your code alternately shows or hides.

Best of all, because you put all the complicated stuff into a function, you can reuse the function to make additional collapsible sections. These sections have the same structure but different contents:

<p>

<img id="Question2Image" src="closed.png" alt=""

onclick="ToggleVisibility('Question2Image','HiddenAnswer2')" />

<b>Can I read more than one answer at a time?</b>

</p>

<div id="HiddenAnswer2" style="display:none">

<p>You can expand as many or as few sections as you want.

Once you've expanded a section, just click again to collapse it back up

out of sight. The only rule is that when you leave this page and come back

later, everything will be hidden all over again. That's just the way

JavaScript and Dynamic HTML work.</p>

</div>

Notice that you have to give each <img> and <div> element a unique ID or your function won’t know which picture to change and which section to hide.

Optionally, you can change this page to give it a different feel but keep the same collapsing behavior. For example, you can make the page easier to use by letting your visitor expand and collapse sections by clicking the heading text (instead of just the image). The easiest way to do this is to pop the image and the bold heading into a <div> element and then add the onclick event attribute to it. Here’s the change you’d make:

<div onclick="ToggleVisibility('Question1Image','HiddenAnswer1')">

<p>

<img id="Question1Image" src="closed.png">

<b>Where has all the information gone?</b>

</p>

</div>

You could even underline the heading text so that it looks like a link, which lets viewers know something will happen if they click it. Use the text-decoration style sheet property to do that (Basic Fonts).

Finally, if you want all your collapsible sections to start off as collapsed, you need to add another script that performs this service. Here’s the <script> block you need, which you can position at the end of your page, just before the closing </body> tag:

<script>

// Hide all sections, one by one.

ToggleVisibility('Question1Image','HiddenAnswer1')

ToggleVisibility('Question2Image','HiddenAnswer2')

...

</script>

You could hide your collapsible sections more easily by setting the display style property on each <div> element with an inline style rule (Using Inline Styles). However, this approach can cause trouble in the unlikely event that a visitor has turned JavaScript off in his browser. In this situation, every section will remain permanently hidden. By using the code approach shown here, you ensure that JavaScript-challenged browsers will simply display all the content, including the collapsible sections. The page won’t be as impressive, but at least nothing goes missing. This approach, called progressive enhancement, makes sure a page works for everyone but adds benefits where possible.

NOTE

You’ll see more collapsible text effects when you tackle collapsible menus in Chapter 15.

Interactive Forms

HTML forms inhabit a corner of the HTML standard you haven’t explored yet. You can use form elements to create the graphical widgets that make up forms, like text boxes, buttons, checkboxes, and lists. Visitors interact with these components, which are commonly called controls, to answer questions and provide information. Figure 14-9 shows an example of an HTML form in action.

HTML forms are an indispensable technology for many websites, but you probably won’t get much mileage out of them. That’s because they’re a hallmark of server-side web applications (Server-Side and Client-Side Programming). In a typical form, a visitor types in information and then clicks a Submit button. The browser then collects that information and sends it back to the web server for further processing. This processing might involve storing the information in a database or sending back another page with different HTML (for example, an error message if the application detects a problem).

Before Google will grant you a Gmail account, you need to submit some seriously detailed information. These text boxes, lists, and drop-down menus are all part of an HTML form

Figure 14-9. Before Google will grant you a Gmail account, you need to submit some seriously detailed information. These text boxes, lists, and drop-down menus are all part of an HTML form.

However, a crafty JavaScript developer can still put a basic form to good use. The difference is that instead of sending information back to a web server, the form collects the data and sends it to a JavaScript routine. That JavaScript code then takes the next step, such as performing a calculation or updating the page.

Form Elements

Every HTML form starts out with a <form> element. Because <form> is a container element, HTML interprets everything inside it as part of your form.

<form>

...

</form>

Form elements are also block elements (The 10 Most Important Elements (and a Few More)). When you create a form, your browser adds a little bit of space and starts you off on a new line.

What goes inside your <form> element? You can put ordinary content (like paragraphs of text) inside or outside it—it really doesn’t matter. But you should always put form controls (those graphical components, like buttons, text boxes, and lists) inside a <form> element. Otherwise, you won’t have any way to capture the information a visitor types in.

To create controls, you use yet another set of HTML elements. Here’s the weird part: most form controls use the exact same element. That element is named <input>, and it represents information you want to get from a visitor. You choose the type of input control using a type attribute. For example, to create a checkbox, you use the checkbox type:

<input type="checkbox" />

To create a text box (where a visitor types in whatever text he wants), you use the text attribute:

<input type="text" />

Every <input> element also supports a value attribute, which you usually use to set the initial state of a control. For example, to put instructions inside a text box when a page first appears, you could use this markup:

<input type="text" value="Enter the first name here" />

Checkboxes are a little different. You can start them off so that they’re turned on by adding the checked attribute, as shown here:

<input type="checkbox" checked />

Not all controls use the <input> element. In fact, there are two notable exceptions. You use the <textarea> element to grab large amounts of text—copy that spans more than one line, like a comment a guest leaves. And you use the <select> element to create a list from which a visitor must select an item. Table 14-3 lists the most common controls. It doesn’t include the new form ingredients that have been added in HTML5 (and that Internet Explorer 8 and earlier don’t recognize).

Table 14-3. Form controls.

CONTROL

HTML ELEMENT

DESCRIPTION

Single-line text box

<input type="text" />

<input type="password" />

Displays a box where visitors can type in text. If you use the password type of text box, the browser won’t display the text. Instead, visitors see an asterisk (*) or a bullet (•) in place of each letter they type, hiding it from prying eyes.

Multiline text box

<textarea>...</textarea>

Shows a large text box that can fit multiple lines of text.

Checkbox

<input type="checkbox" />

Shows a checkbox you can turn on or off.

Radio button

<input type="radio" />

Shows a radio button (a circle) you can turn on or off. Usually, you have a group of radio buttons next to one another, in which case the visitor can select only one.

Button

<input type="submit" />

<input type="image" />

<input type="reset" />

<input type="button" />

Shows the standard clickable button. A submit button always gathers up the form data and sends it to its destination. An image button does the same thing but lets you display a clickable picture instead of the standard text-on-a-button. A reset button clears the visitor’s selections and text from all the inputcontrols. A button button doesn’t do anything unless you add some JavaScript code.

List

<select>...</select>

Shows a list where your visitor can select one or more items. You add an <option> element for each item in the list.

A Basic Form

To create a complete form, you mix and match <input> elements with ordinary HTML. Consider the page shown in Figure 14-10. It provides several text boxes where a visitor types in numbers, and then it uses those numbers to determine the guest’s body mass index (BMI) when he clicks the Calculate button.

Building this form is surprisingly easy. The trickiest part is creating the function that powers the underlying calculations.

Most visitors are concerned about what this BMI calculator says about their health, but you can see single-line text boxes and a submit button (labeled “Calculate” here) at work

Figure 14-10. Most visitors are concerned about what this BMI calculator says about their health, but you can see single-line text boxes and a submit button (labeled “Calculate” here) at work.

This function needs several pieces of information, corresponding to the values in the three text boxes (feet, inches, and pounds). It also needs the name of the element where it should display the results. Here’s how the function starts:

<script>

function CalculateBMI(feet, inches, pounds, resultElementName) {

NOTE

You could create a CalculateBMI() function that doesn’t use any parameters. Instead, the function could just search for all the controls on the page by name. However, using parameters is always a good idea, because it makes your code more flexible. For example, if you decide to change the names of the controls in your form, you don’t need to change the code inside theCalculateBMI() function, just the line of code that calls CalculateBMI(). You’re also able to move your function to a different page, or—in a more advanced scenario—to use it with data that you’ve retrieved from somewhere else other than a form.

The function code that follows isn’t much different from what you’ve seen before. It begins by using a Number() function that’s part of the JavaScript standard. This function converts the text a visitor types in to numbers that the function can use in calculations. If you don’t take this step, you might still get the right answer (sometimes), because JavaScript can automatically convert text strings into numbers as needed. However, there’s a catch—if you try to add two numbers and JavaScript thinks they’re strings, it will just join the two strings into one piece of text, so 1+1 would get you 11. This mistake can really scramble your calculations, so it’s best to always use the Number() function, like so:

inches = Number(inches)

pounds = Number(pounds)

feet = Number(feet)

The actual calculation isn’t too interesting. It’s taken straight from the definition of body mass index, which you can find on the Internet.

var totalInches = (feet * 12) + inches

Finally, the function displays the result:

var resultElement = document.getElementById(resultElementName)

resultElement.innerHTML =

Math.round(pounds * 703 * 10 / totalInches / totalInches) / 10

}

</script>

Building the form that uses this function is the easy part. All you do is create the text boxes with <input> elements and give them names you can easily remember. In the example below, the form uses a table to make sure the text boxes line up neatly next to one another:

<form action="">

<table>

<tr>

<td>Height: </td>

<td><input type="text" name="feet" /> feet</td>

</tr>

<tr>

<td> </td>

<td><input type="text" name="inches" /> inches</td>

</tr>

<tr>

<td>Weight: </td>

<td><input type="text" name="pounds" /> pounds</td>

</tr>

</table>

Finally, at the bottom of the form, you create a button that calls the CalculateBMI() function using the form’s values. To have the button make this call, you need to program your page to react to the onclick event. To look up a value in a form, you don’t need the getElementById()function. Instead, you find it by name, using the this.form object, which represents the current form:

<p>

<input type="button" name="calc" value="Calculate"

onclick="CalculateBMI(this.form.feet.value, this.form.inches.value,

this.form.pounds.value, 'result')" />

</p>

</form>

The final ingredient is the element that displays the result. In this case, because you want the result to appear inside another paragraph, the <span> element makes more sense than a <div> element.

<p>

Your BMI: <span id="result"></span>

</p>

You can use all sorts of other form-related scripts. For example, you can check the information that people enter into forms for errors before letting them continue from one page to another. To learn more about these scripts, you need to take your search to the Web, as described in the next section.

Scripts on the Web

JavaScript is a truly powerful tool. If you’re a die-hard alpha nerd who likes to program your TiVo to talk to your BlackBerry, you’ll enjoy long nights of JavaScript coding. However, if you don’t like to lie awake wondering what var howMany = (trueTop>1?“s” :“”); really means, you’ll probably be happier letting someone else do the heavy lifting.

If you fall into the nonprogrammer camp, this chapter has some good news. The Web is flooded with free JavaScript. Most of the time, these scripts include step-by-step instructions that explain where to put the functions, what elements to use in your page, and how to hook your elements up to functions using events.

However, there’s a downside to free JavaScript. As you learned at the beginning of this chapter, JavaScript dates back to the early days of the Internet, and many JavaScript sites are nearly as old. As a result, they may feature garish formatting, out-of-date browser compatibility information (for example, they might warn you that a script doesn’t work on the long-deceased Netscape browser), and old approaches that have been replaced with more modern techniques. Many JavaScript sites are also chock-full of ads.

If these issues haven’t discouraged you, here are a few starting points for your JavaScript search:

www.dynamicdrive.com

This site provides a set of respectable scripts that emphasize Dynamic HTML. Some scripts create exotic effects, like glowing green letters that tumble down the page, Matrix-style.

http://lokeshdhakar.com/projects/lightbox2

This site has just a single script, but it’s one of the most popular effects on the Web. If you’ve ever clicked a picture thumbnail and had it expand to full size (while the rest of the page goes subtly dark), you’ve seen a variation of this effect.

http://tinyurl.com/webmonkey-js

The Web Monkey site offers a small set of old but still useful JavaScript tutorials, which can help you get oriented in the language—and pick up a few core techniques.

Using this list, you can dig up everything from little frills to complete, functioning Tetris clones. But keep in mind that a script is only as good as the coder who created it. Even on sites with good quality control, you could stumble across a script that doesn’t work on all browsers or slows your page down to a crawl. As a rule of thumb, always try out each script thoroughly before you start using it on your site.

TIP

The hallmark of a good script site is that it’s easy to navigate. You’ll know you’ve found a bad script site if it’s so swamped with ads and pop-ups that you can’t find the scripts themselves.

Finding a Simple Script

Ready to hunt for scripts online? The next series of steps takes you through the process from beginning to end.

1. Fire up your browser and choose your site from the list above.

For this example, use www.dynamicdrive.com.

2. Choose the category you want from the site’s home page.

In this case, go to the Documents Effects category. For a sample of what else you can find, see the box on Script Categories.

3. Scroll through the list of scripts in your category (Figure 14-11), and then click one.

In this case, use the Top-Down Stripy Curtain script.

4. The next page shows an example of the script (Figure 14-12).

Once the demo is over, you’ll see a script description, the author’s name, and a link to the script (if it isn’t already displayed on the page). Underneath all this information are the step-by-step instructions for using the script.

The Top-Down Stripy Curtain script is good to go, with support for all modern browsers

Figure 14-11. The Top-Down Stripy Curtain script is good to go, with support for all modern browsers.

UP TO SPEED: SCRIPT CATEGORIES

To get a handle on the types of dynamic HTML scripts available, look through the categories at Dynamic Drive (www.dynamicdrive.com). Here’s a sampling of what you’ll find:

o The Calendars category scripts produce nifty HTML that creates calendars—great for displaying important dates or letting visitors plan in advance.

o The Date & Time category offers virtual timekeepers and countdown clocks.

o The Document Effects category provides page transitions and background effects (like fireworks or floating stars).

o The Dynamic Content category has sliding menus, sticky notes, and scrollable panels.

o The Form Effects category includes scripts that let you manage forms (see Interactive Forms). You can use them to make sure visitors submit forms only once, to check for invalid entries, and more.

o The Games category offers full-blown miniature games, like tic-tac-toe and Tetris. These games stretch the capabilities of JavaScript and dynamic HTML as far as they can go.

o The Image Effects category has slideshow and image-gallery scripts, along with images that change when you point to them.

o The Links & Tooltips category includes fancy links that flash, button tricks, and pop-up text boxes that capture your visitors’ attention.

o The Menus & Navigation category provides handy collapsible menus and navigation bars that let visitors move through your site, like the components you’ll see in Chapter 15.

o The Mouse and Cursor category offers scripts that change the mouse pointer and add those annoying mouse trails (pictures that follow the mouse pointer wherever it goes).

o The Scrollers category has marquee-style scrolling text, like you might see in a news ticker.

o The Text Animations category scripts bring text to life, making it shake, fly, glow, or take on even more bizarre characteristics.

o The User/System Preference category scripts dig up information about the browser that’s currently displaying your page.

o The Window and Frames category has scripts for a dozen types of pop-up windows.

Here’s the Top-Down Stripy Curtain script in action. It first fills the page with a solid green foreground and then exposes the content underneath by removing alternating strips of color, some of which fall from the top, while others rise from the bottom. It all happens in a flash

Figure 14-12. Here’s the Top-Down Stripy Curtain script in action. It first fills the page with a solid green foreground and then exposes the content underneath by removing alternating strips of color, some of which fall from the top, while others rise from the bottom. It all happens in a flash.

5. Follow the instructions to copy and paste the different parts of the script into your page (Figure 14-13).

You often get a set of functions you need to put in the <head> portion of your page and then some HTML elements you need to place in the <body> section. In some cases, you can customize the scripts—for example, you might modify numbers and other values to tweak the script code, or change the HTML elements to provide different content.

NOTE

Many scripts include a set of comments with author information. If they do, the standard practice is to keep these comments in your script file, so other developers who check out your site will know where the code came from. This practice is just part of giving credit where credit’s due. Ordinary web visitors won’t even think to look at the script code, so they won’t have any idea whether or not you wrote the script from scratch.

JavaScript Libraries

In the years since JavaScript was first created, coders have shifted focus to JavaScript libraries. These libraries go beyond a hodgepodge of individual scripts—they offer a whole new set of JavaScript capabilities, extending the language so you don’t need to write every piece of interactive code from scratch.

The Top-Down Stripy Curtain script has two components. The first is a style definition that produces the curtain’s solid-color background. The second part creates the curtain itself (as a <div> element), which disappears to expose the page’s content and includes the code that performs the transition. Copy both of these components to any page, and you’re set. (For even better organization, consider placing the code in a separate JavaScript file, as described on page 472.)

Figure 14-13. The Top-Down Stripy Curtain script has two components. The first is a style definition that produces the curtain’s solid-color background. The second part creates the curtain itself (as a <div> element), which disappears to expose the page’s content and includes the code that performs the transition. Copy both of these components to any page, and you’re set. (For even better organization, consider placing the code in a separate JavaScript file, as described on page 472.)

Even better, the programs you find in JavaScript libraries have been tested to ensure that they work in all of today’s browsers—sometimes using huge reams of behind-the-scenes code to do so. And super-smart programmers use JavaScript libraries to build even more useful scripts and self-contained web widgets, like slideshows, product carousels, dynamic charts, and image magnifiers. These slick scripts go far beyond the examples you’ll find on an old-fashioned JavaScript site. For all these reasons, professional web developers almost always use JavaScript libraries.

When you first dip your toe into the world of JavaScript libraries, the best starting point is the wildly successful jQuery library (http://jquery.com). It’s by far the most popular JavaScript library, playing a major or minor role in more than half of the world’s most trafficked websites. More than a dozen other JavaScript libraries also flourish on the Web, including MooTools (http://mootools.net) and Dojo (http://dojotoolkit.org).

If you’ve never touched a line of programming until this chapter, JavaScript libraries might not be for you. That’s because they’re designed for other programmers—people who want to create their own JavaScript-fueled web pages, but don’t want to reinvent the wheel. Mere mortals can use them, but there’s a steep learning curve. If you’re just getting started, you can check out JavaScript: The Missing Manual (O’Reilly), which describes JavaScript basics and the ins and outs of the jQuery library.