Chapter 1
In This Chapter
Adding JavaScript code to your pages
Setting up your environment for JavaScript
Creating variables
Inputting and outputting with modal dialogs
Using concatenation to build text data
Understanding data types
Using string methods and properties
Using conversion functions
Web pages are defined by the HTML code and fleshed out by CSS. But to make them move and breathe, sing, and dance, you need to add a programming language or two. If you thought building web pages was cool, you're going to love what you can do with a little programming. Programming is what makes pages interact with the user. Interactivity is the “new” in “new media” (if you ask me, anyway). Learn to program, and your pages come alive.
Sometimes people are nervous about programming. It seems difficult and mysterious, and only super-geeks do it. That's a bunch of nonsense. Programming is no more difficult than HTML and CSS. It's a natural extension, and you're going to like it.
In this chapter, you discover how to add code to your web pages. You use a language called JavaScript, which is already built into most web browsers. You don't need to buy any special software, compilers, or special tools because you build JavaScript just like HTML and CSS — in an ordinary text editor or a specialty editor such as Aptana.
JavaScript is a programming language first developed by Netscape Communications. It is now standard on nearly every browser. You should know a few things about JavaScript right away:
Don't go telling people you're programming in Java. Java people love to act all superior and condescending when JavaScript programmers make this mistake. If you're not sure, ask a question on my web page. I can help you with either language.
Even though JavaScript is a programming language, it is still basically text. Because it's normally embedded in a web page, you can work in the same text editor you're using for HTML and CSS. I'm a big fan of Komodo because the same general features you've been enjoying in HTML and CSS are even more important when you're writing code in a more formal programming language:
In addition to your editor, you should think again about your browser when you're testing JavaScript code. All the major browsers support JavaScript, and the support for JavaScript is relatively similar across the browsers (at least for the stuff in this chapter). However, browsers aren't equal when it comes to testing your code.
Things will go wrong when you write JavaScript code, and the browser is responsible for telling you what went wrong. Chrome is by far the favorite browser for JavaScript programmers today because it has extremely powerful editing tools. The Firebug plug-in adds many of the same features to other browsers, but it's probably best to start with Chrome because everything you need is already built-in. See Chapter 3 of this mini-book for much more on debugging JavaScript code.
The foundation of any JavaScript program is a standard web page like the ones featured in the first three minibooks.
To create your first JavaScript program, you need to add JavaScript code to your pages. Figure 1-1 shows the classic first program in any language.
This page has a very simple JavaScript program in it that pops up the phrase “Hello, World!” in a special element called a dialog box. It's pretty cool.
Here's an overview of the code:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>HelloWorld.html</title>
<script type = "text/javascript">
// Hello, world!
alert("Hello, World!");
</script>
</head>
<body>
</body>
</html>
As you can see, this page contains nothing in the HTML body. You can incorporate JavaScript with HTML content. For now, though, you can simply place JavaScript code in the head area in a special tag and make it work.
JavaScript code is placed in your web page via the <script> tag. JavaScript code is placed inside the <script></script> pair. The <script> tag has one required attribute, type, which will usually be text/javascript. (Other types are possible, but they're rarely used.)
Just like HTML and CSS, comments are important. Because programming code can be more difficult to decipher than HTML or CSS, it's even more important to comment your code in JavaScript than it is in these environments. The comment character in JavaScript is two slashes (//).The browser ignores everything from the two slashes to the end of the line. You can also use a multi-line comment (/* */) just like the one in CSS.
You can output data in JavaScript in a number of ways. In this chapter, I focus on the simplest to implement and understand — the alert().
This technique pops up a small dialog box containing text for the user to read. The alert box is an example of a modal dialog. Modal dialogs interrupt the flow of the program until the user pays attention to them. Nothing else will happen in the program until the user acknowledges the dialog by clicking the OK button. The user can't interact with the page until he clicks the button.
Each command in JavaScript ends with a semicolon (;) character. The semicolon in most computer languages acts like the period in English. It indicates the end of a logical thought. Usually, each line of code is also one line in the editor.
Computer programs get their power by working with information. Figure 1-2 shows a program that gets user data from the user to include in a customized greeting.
This program introduces a new kind of dialog that allows the user to enter some data. The information is stored in the program for later use. After the user enters her name, she gets a greeting, as shown in Figure 1-3.
The rest of the greeting happens in a second dialog box, shown in Figure 1-4. It incorporates the username supplied in the first dialog box.
The output may not seem that incredible, but take a look at the source code to see what's happening:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>prompt.html</title>
<script type = "text/javascript">
// from prompt.html
var person = "";
person = prompt("What is your name?");
alert("Hi");
alert(person);
</script>
</head>
<body>
</body>
</html>
This program is interesting because it allows user interaction. The user can enter a name, which is stored in the computer and then returned in a greeting. The key to this program is a special element called a variable. Variables are simply places in memory for holding data. Any time you want a computer program to “remember” something, you can create a variable and store your information in it.
Variables typically have the following characteristics:
The prompt statement does several interesting things:
This program uses the alert() statement to begin a greeting to the user. The first alert works just like the one from the helloWorld program, described earlier in this chapter in the “Writing Your First JavaScript Program” section:
alert("Hi");
The content of the parentheses is the text you want the user to see. In this case, you want the user to see the literal value “Hi”.
The second alert() statement is a little bit different:
alert(person);
This alert() statement has a parameter with no quotes. Because the parameter has no quotes, JavaScript understands that you don't really want to say the text person. Instead, it looks for a variable named person and returns the value of that variable.
The variable can take any name, store it, and return a customized greeting.
To have a greeting and a person's name on two different dialogs seems a little awkward. Figure 1-5 shows a better solution.
The program asks for a name again and stores it in a variable. This time, the greeting is combined into one alert (see Figure 1-6), which looks a lot better.
The secret to Figure 1-6 is one of those wonderful gems of the computing world: a really simple idea with a really complicated name. The term concatenation is a delightfully complicated word for a basic process. Look at the following code, and you see that combining variables with text is not all that complicated:
<script type = "text/javascript">
//from concat.html
var person = "";
person = prompt("What is your name?");
alert("Hi there, " + person + "!");
</script>
The program concat.html contains two kinds of text. "Hi there, " is a literal text value. That is, you really mean to say “Hi there, " (including the comma and the space). person is a variable. (For more on variables, see the section “Introducing Variables,” earlier in this chapter.)
You can combine literal values and variables in one phrase if you want:
alert("Hi there, " + person + "!");
The secret to this code is to follow the quotes. "Hi there, " is a literal value because it is in quotes. On the other hand, person is a variable name because it is not in quotes; "!" is a literal value. You can combine any number of text snippets together with the plus sign.
Using the plus sign to combine text is called concatenation. (I told you it was a complicated word for a simple idea.)
You may be curious about the extra space between the comma and the quote in the output line:
alert("Hi there, " + person + "!");
This extra space is important because you want the output to look like a normal sentence. If you don't have the space, the computer doesn't add one, and the output looks like this:
Hi there,Rachael!
The person variable used in the previous program is designed to hold text. Programmers (being programmers) devised their own mysterious term to refer to text. In programming, text is referred to as string data.
JavaScript (and many other modern programming languages) uses a powerful model called object-oriented programming (OOP). This style of programming has a number of advantages. Most important for beginners, it allows you access to some very powerful objects that do interesting things out of the box.
Objects are used to describe complicated things that can have a lot of characteristics — like a cow. You can't really put an adequate description of a cow in an integer variable.
In many object-oriented environments, objects can have the following characteristics. (Imagine a cow object for the examples.)
I describe each of these ideas throughout this minibook because not all objects support all these characteristics.
If you have a variable of type cow, it describes a pretty complicated thing. This thing might have properties, methods, and events, all of which can be used together to build a good representation of a cow. (Believe it or not, I've built cow programming constructs more than once in my life — and you thought programming was dull!)
Most variable types in Java are actually objects, and most JavaScript objects have a full complement of properties and methods; many even have event handlers. Master how these things work and you've got a powerful and compelling programming environment.
When you assign text to a variable, JavaScript automatically treats the variable as a string object. The object instantly takes on the characteristics of a string object. Strings have a couple of properties and a bunch of methods. The one interesting property (at least for beginners) is length. Look at the example in Figure 1-7 to see the length property in action.
That's kind of cool how the program can figure out the length of a phrase. The cooler part is the way it works. As soon as you assign a text value to a variable, JavaScript treats that variable as a string, and because it's a string, it now has a length property. This property returns the length of the string in characters. Here's how it's done in the code.
<script type = "text/javascript">
//from nameLength.html
var person = prompt("Please enter your name.");
var length = person.length;
alert("Hi, " + person + "!");
alert("The name " + person + " is " + length + " characters long.");
</script>
A property is used like a special subvariable. For example, person is a variable in the previous example. person.length is the length property of the person variable. In JavaScript, an object and a variable are connected by a period (with no spaces).
The length property is kind of cool, but the string object has a lot more up its sleeve. Objects also have methods (things the object can do). Strings in JavaScript have all kinds of methods. Here are a few of my favorites:
Like properties, methods are attached to an object by the period. Methods are distinguished by a pair of parentheses, which sometimes contain special information called parameters.
The best way to see how methods work is to look at some in action. Look at the code for stringMethods.html:
<script type = "text/javascript">
//from stringMethods.html
var text = new String;
text = prompt("Please enter some text.");
alert("I'll shout it out:");
alert(text.toUpperCase());
alert("Now in lowercase...");
alert(text.toLowerCase());
alert("The first 'a' is at letter...");
alert(text.indexOf("a"));
alert("The first three letters are ...");
alert(text.substring(0, 3));
</script>
Figure 1-8 displays the output produced by this program.
In this example, I explicitly defined text as a string variable by saying
var text = new String;
JavaScript does not require you to explicitly determine the type of a variable, but you can do so, and this is sometimes helpful.
You can see from the preceding code that methods are pretty easy to use. When you have a string variable, you can invoke the variable name followed by a period and the method name. Some methods require more information to do their job. Here are the specifics:
JavaScript isn't too fussy about whether a variable contains text or a number, but the distinction is still important because it can cause some surprising problems. To illustrate, take a look at a program that adds two numbers together, and then see what happens when you try to get numbers from the user to add.
First, take a look at the following program:
<script type = "text/javascript">
//from addNumbers.html
var x = 5;
var y = 3;
var sum = x + y;
alert(x + " plus " + y + " equals " + sum);
</script>
(As usual for this chapter, I'm only showing the script part because the rest of the page is blank.)
This program features three variables. I've assigned the value 5 to x and 3 to y. I then add x + y and assign the result to a third variable, sum. The last line prints the results, which are also shown in Figure 1-9.
Note a few important things from this example:
var x = 5;
The natural extension of the addNumbers.html program is a feature that allows the user to input two values and then returns the sum. This program can be the basis for a simple adding machine. Here's the JavaScript code:
<script type = "text/javascript">
//from addInputWrong.html
var x = prompt("first number:");
var y = prompt("second number:");
var sum = x + y;
alert(x + " plus " + y + " equals " + sum);
</script>
This code seems reasonable enough. It asks for each value and stores them in variables. It then adds the variables and returns the results, right? Well, look at Figure 1-10 to see a surprise.
Something's obviously not right here. To understand the problem, you need to see how JavaScript makes guesses about data types (see the next section).
Ultimately, all the information stored in a computer, from music videos to e-mails, is stored as a bunch of ones and zeroes. The same value 01000001 can mean all kinds of things: It may mean the number 65 or the character A. (In fact, it does mean both those things in the right context.) The same binary value may mean something entirely different if it's interpreted as a real number, a color, or a part of a sound file.
The theory isn't critical here, but one point is really important: Somehow the computer has to know what kind of data is stored in a specific variable. Many languages, such as C and Java, have all kinds of rules about defining data. If you create a variable in one of these languages, you have to define exactly what kind of data will go in the variable, and you can't change it.
JavaScript is much more easygoing about variable types. When you make a variable, you can put any kind of data in it that you want. In fact, the data type can change. A variable can contain an integer at one point, and the same variable may contain text in another part of the program.
JavaScript uses the context to determine how to interpret the data in a particular variable. When you assign a value to a variable, JavaScript puts the data in one of the following categories:
Most of the time, when you make a variable, JavaScript guesses right, and you have no problems. But sometimes, JavaScript makes some faulty assumptions, and things go wrong.
I use the plus sign in two ways throughout this chapter. The following code uses the plus sign in one way (concatenating two string values):
var x = "Hi, ";
var y = "there!";
result = x + y;
alert(result);
In this code, x and y are text variables. The result = x + y line is interpreted as “concatenate x and y,” and the result is "Hi, there!"
Here's the strange thing: The following code is almost identical.
var x = 3;
var y = 5;
result = x + y;
alert(result);
Strangely, the behavior of the plus sign is different here, even though the statement result = x + y is identical in the two code snippets.
In this second case, x and y are numbers. The plus operator has two entirely different jobs. If it's surrounded by numbers, it adds. If it's surrounded by text, it concatenates.
That's what happened to the first adding machine program. When the user enters data in prompt dialogs, JavaScript assumes that the data is text. When I try to add x and y, it “helpfully” concatenates instead.
If JavaScript is having a hard time figuring out what type of data is in a variable, you can give it a friendly push in the right direction with some handy conversion functions, as shown in Table 1-1.
The conversion functions are incredibly powerful, but you only need them if the automatic conversion causes you problems. Here's how they work:
With all this conversion knowledge in place, it's pretty easy to fix up the addInput program so that it works correctly. Just use parseFloat() to force both inputs into floating-point values before adding them. You don't have to explicitly convert the result to a string. That's automatically done when you invoke the alert() method.
// from addInput.html
var x = prompt("first number:");
var y = prompt("second number:");
var sum = parseFloat(x) + parseFloat(y);
alert(x + " plus " + y + " equals " + sum);
You can see the program works correctly in Figure 1-11.
Conversion methods allow you to ensure that the data is in exactly the format you want.