Chapter 1

Getting Started with JavaScript

In This Chapter

arrow Adding JavaScript code to your pages

arrow Setting up your environment for JavaScript

arrow Creating variables

arrow Inputting and outputting with modal dialogs

arrow Using concatenation to build text data

arrow Understanding data types

arrow Using string methods and properties

arrow 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.

Working in JavaScript

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:

  • It's a real programming language. Don't let anybody tell you otherwise. Sure, JavaScript doesn't have all the same features as a monster, such as C++ or VB.NET, but it still has all the hallmarks of a complete programming language.
  • It's not Java. Sun Microsystems developed a language called Java, which is also sometimes used in web programming. Despite the similar names, Java and JavaScript are completely different languages. The original plan was for JavaScript to be a simpler language for controlling more complex Java applets, but that never really panned out.

    warning.eps 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.

  • It's a scripting language. As programming languages go, JavaScript's pretty friendly. It's not quite as strict or wordy as some other languages. It also doesn't require any special steps (such as compilation), so it's pretty easy to use. These things make JavaScript a great first language.

Choosing a JavaScript editor

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:

  • Syntax highlighting: Like it does with HTML and CSS, Komodo automatically adjusts code colors to help you see what's going on in your program. As you see in the later sidebar “Concatenation and your editor,” this adjustment can be a big benefit when things get complicated.
  • Code completion: When you type the name of an object, Komodo provides you with a list of possible completions. This shortcut can be really helpful because you don't have to memorize all the details of the various functions and commands.
  • Pop-up help: As you enter a function that Komodo recognizes, it automatically pops up a help menu explaining what the function does and what parameters could be placed there.

Picking your test browser

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.

Writing Your First JavaScript Program

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.

9781118289389-fg1801.tif

Figure 1-1: A JavaScript program caused this little dialog box to pop up!

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.

Embedding your JavaScript code

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.)

Creating comments

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.

Using the alert() method for output

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.

remember.eps Modal dialogs may seem a bit rude. In fact, you probably won't use them much after you discover other input and output techniques. The fact that the dialog box demands attention makes it a very easy tool to use when you start programming. I use it (and one of its cousins) throughout this chapter because it's easy to understand and use. Also, note that the dialog will be slightly different from browser to browser and between operating systems. There isn't really a way to control more precisely how dialogs work, but they're easy. You'll learn much more sophisticated means of interacting with the user in the next few chapters.

Adding the semicolon

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.

tip.eps To tell the truth, JavaScript will usually work fine if you leave out the semicolons. However, you should add them anyway because they help clarify your meaning. Besides, many other languages, including PHP (see Book V), require semicolons. You may as well start a good habit now.

Introducing Variables

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.

9781118289389-fg1802.tif

Figure 1-2: First, the program asks the user for a name.

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.

9781118289389-fg1803.tif

Figure 1-3: The beginning of the greeting. Press the button for the rest.

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.

tip.eps Your browser might or might not have the ‘prevent this page from creating additional dialogs’ checkbox. This is actually a nice debugging feature in Chrome. It will be possible to create programs that get out of control. Chrome noticed two dialogs popping up in a row and thinks we might be in one of those dangerous situations, called an endless loop. (More on loops, endless and otherwise, in Chapter 3 of this mini-book.) For now, just press the OK button because this program is acting as intended. Soon enough, we'll stop using dialogs because they're just too annoying.

9781118289389-fg1804.tif

Figure 1-4: Now the greeting is complete.

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>

Creating a variable for data storage

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 var statement: You can indicate that you're creating a variable with the var command.
  • A name: When you create a variable, you're required to give it a name.
  • An initial value: It's useful to give each variable a value immediately.
  • A data type: JavaScript automatically determines the type of data in a variable (more on this in the upcoming “Understanding Variable Types” section), but you should still be clear in your mind what type of data you expect a variable to contain.

Asking the user for information

The prompt statement does several interesting things:

  • Pops up a dialog box. This modal dialog box is much like the one the alert() method creates.
  • Asks a question. The prompt() command expects you to ask the user a question.
  • Provides space for a response. The dialog box contains a space for the user to type a response and buttons for the user to click when he's finished or wants to cancel the operation.
  • Passes the information to a variable. The purpose of a prompt() command is to get data from the user, so prompts are nearly always connected to a variable. When the code is finished, the variable contains the indicated value.

Responding to the user

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.

Using Concatenation to Build Better Greetings

To have a greeting and a person's name on two different dialogs seems a little awkward. Figure 1-5 shows a better solution.

9781118289389-fg1805.tif

Figure 1-5: Once again, I ask the user for a name.

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.

9781118289389-fg1806.tif

Figure 1-6: Now the user's name is integrated into the greeting.

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>

tip.eps For the sake of brevity, I include only the script tag and its contents throughout this chapter. The rest of this page is a standard blank HTML page. You can see the complete document on the website. I do include a comment in each JavaScript snippet that indicates where you can get the entire file on the companion website.

Comparing literals and variables

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.)

Including spaces in your concatenated phrases

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!

remember.eps You need to construct the output as it should look, including spaces and punctuation.

Understanding the String Object

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.

tip.eps The term string comes from the way text is stored in computer memory. Each character is stored in its own cell in memory, and all the characters in a word or phrase reminded the early programmers of beads on a string. Surprisingly poetic for a bunch of geeks, huh?

Introducing object-based programming (and cows)

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.)

  • Properties: Characteristics about the object, such as breed and age
  • Methods: Things the objects can do, such as moo() and giveMilk()
  • Events: Stimuli the object responds to, such as onTip

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.

technicalstuff.eps Okay, before you send me any angry e-mails, I know debate abounds about whether JavaScript is a truly object-oriented language. I'm not going to get into the (frankly boring and not terribly important) details in this beginner book. We're going to call JavaScript object-oriented for now because it's close enough for beginners. If that bothers you, you can refer to JavaScript as an object-based language. Nearly everyone agrees with that. You can find out more information on this topic throughout this minibook while you discover how to make your own objects in Chapter 4 and use HTML elements as objects in Chapter 2.

Investigating the length of a string

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.

9781118289389-fg1807.tif

Figure 1-7: This program reports the length of any text.

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).

technicalstuff.eps The string object in JavaScript has only two other properties (constructor and prototype). Both of these properties are needed only for advanced programming, so I skip them for now.

Using string methods to manipulate text

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:

  • toUpperCase() makes an entirely uppercase copy of the string.
  • toLowerCase() makes an entirely lowercase copy of the string.
  • substring() returns a specific part of the string.
  • indexOf() determines whether one string occurs within another.

technicalstuff.eps The string object has many other methods, but I'm highlighting the preceding because they're useful for beginners. Many string methods, such as big() and fontColor(), simply add HTML code to text. They aren't used very often because they produce HTML code that won't validate, and they don't really save a lot of effort anyway. Some other methods, such as search(), replace(), and slice(), use advanced constructs like arrays and regular expressions that aren't necessary for beginners. (To find out more about working with arrays, see Chapter 4 of this minibook. You can find out more about regular expressions in Chapter 5.)

tip.eps Don't take my word for it. Look up the JavaScript string object (in one of the many online JavaScript references) and see what properties and methods it has.

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.

9781118289389-fg1808.tif

Figure 1-8: String methods can be fun.

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.

tip.eps Here's another cool thing about Komodo Edit. When you type text, Komodo understands that you're talking about a string variable and automatically pops up a list of all the possible properties and methods of the string object. I wish I had that when I started doing this stuff!

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:

  • toUpperCase() and toLowerCase() take the value of the variable and convert it entirely to the given case. This method is often used when you aren't concerned about the capitalization of a variable.
  • indexOf(substring) returns the character position of the substring within the variable. If the variable doesn't contain the substring, it returns the value –1.
  • substring(begin, end) returns the substring of the variable from the beginning character value to the end.

Understanding Variable Types

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.

Adding numbers

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.

9781118289389-fg1809.tif

Figure 1-9: This program (correctly) adds two numbers together.

Note a few important things from this example:

  • You can assign values to variables. It's best to read the equal sign as “gets” so that the first assignment is read as “variable x gets the value 5.”

        var x = 5;

  • Numeric values aren't enclosed in quotes. When you refer to a text literal value, it's always enclosed in quotes. Numeric data, such as the value 5, isn't placed in quotes.
  • You can add numeric values. Because x and y both contain numeric values, you can add them together.
  • You can replace the results of an operation in a variable. The result of the calculation x + y is placed in a variable called sum.
  • Everything works as expected. The behavior of this program works as expected. That's important because it's not always true. (You can see an example of this behavior in the next section — I love writing code that blows up on purpose!)

Adding the user's numbers

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.

9781118289389-fg1810.tif

Figure 1-10: Wait a minute… 3 + 5 = 35?

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).

The trouble with dynamic data

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:

  • Integers are whole numbers (no decimal part). They can be positive or negative values.
  • A floating point number has a decimal point — for example, 3.14. You can also express floating point values in scientific notation, such as 6.02e23 (Avogadro's number –6.02 times 10 to the 23rd). Floating point numbers can also be negative.
  • A Boolean value can only be true or false.
  • Text is usually referred to as string data in programming languages. String values are usually enclosed in quotes.
  • Arrays and objects are more complex data types that you can ignore for now.

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.

The pesky plus sign

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.

tip.eps There's a fancy computer science word for this phenomenon (an operator doing different things in different circumstances). Those Who Care about Such Things call this mechanism an overloaded operator. Smart people sometimes have bitter arguments about whether overloaded operators are a good idea because they can cause problems like this one, but they can also make things easier in other contexts. I'm not going to enter into that debate here. It's not really a big deal, as long as you can see the problem and fix it.

Changing Variables to the Desired Type

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.

1801

Using variable conversion tools

The conversion functions are incredibly powerful, but you only need them if the automatic conversion causes you problems. Here's how they work:

  • parseInt() is used to convert text to an integer. If you put a text value inside the parentheses, the function returns an integer value. If the string has a floating-point representation (“4.3” for example), an integer value (4) is returned.
  • parseFloat() converts text to a floating-point value.
  • toString() takes any variable type and creates a string representation. Usually, using this function isn't necessary to use because it's invoked automatically when needed.
  • eval() is a special method that accepts a string as input. It then attempts to evaluate the string as JavaScript code and return the output. You can use this method for variable conversion or as a simple calculator — eval(“5 + 3”) returns the integer 8.
  • Math.ceil() is one of several methods of converting a floating-point number to an integer. This technique always rounds upward, so Math.ceil(1.2) is 2, and Math.ceil(1.8) is also 2.
  • Math.floor() is similar to Math.ceil(), except it always rounds downward, so Math.floor(1.2) and Math.floor(1.8) will both evaluate to 1.
  • Math.round() works like the standard rounding technique used in grade school. Any fractional value less than .5 rounds down, and greater than or equal to .5 rounds up, so Math.round(1.2) is 1, and Math.round(1.8) is 2.

Fixing the addInput code

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.

9781118289389-fg1811.tif

Figure 1-11: Now the program asks for input and correctly returns the sum.

Conversion methods allow you to ensure that the data is in exactly the format you want.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset