1. Getting Acquainted with JavaScript

In This Chapter

What JavaScript Is 2

JavaScript Isn’t Java 3

Where JavaScript Came From 5

What JavaScript Can Do 6

What JavaScript Can’t Do 7

What Is Ajax? 8

The Snap-Together Language 11

Handling Events 14

Values and Variables 15

Writing JavaScript-Friendly HTML 17

What Tools to Use? 20

For Web site creators, the evolution of HTML has been a mixed blessing. In the early days of the World Wide Web, HTML was fairly simple, and it was easy to learn everything you needed to put together Web pages.

As the Web grew, page designers wanted their pages to interact with users, and it soon became obvious that HTML was insufficient to handle the demand. Netscape invented JavaScript as a way to control the browser and add pizzazz and interactivity to Web pages.

Since its creation, JavaScript has evolved quite a bit (although occasionally in different directions, depending on the browser). Later, we’ll discuss JavaScript’s evolution in detail.

In this chapter, you’ll learn what JavaScript is (and what it isn’t); what it can do (and what it can’t); some of the basics of the JavaScript language; and you’ll get an introduction to Ajax, the combination of JavaScript with other technologies that has enabled a wave of interactivity and creativity for Web sites.

What JavaScript Is

JavaScript is a programming language that you can use to add interactivity to your Web pages. But if you’re not a programmer, don’t panic; there are lots of JavaScripts available on the Web that you can copy and modify for your own use with a minimum of effort. In fact, standing on the shoulders of other programmers in this way is a great technique for getting comfortable with JavaScript.

To make it easier for you to get up and running with JavaScript, we have set up a Web site that supplements this book. We’ve included all the scripts in the book (so you don’t have to type them in yourself!), as well as additional notes, addenda, and updates. You can find our site at www.javascriptworld.com.

You’ll often see JavaScript referred to as a “scripting language,” with the implication that it is somehow easier to script than to program. It’s a distinction without a difference, in this case. A JavaScript script is a program that either is contained internally in an HTML page (the original method of scripting) or resides in an external file (the now-preferred method). On HTML pages, because it is enclosed in the <script> tag, the text of the script doesn’t appear on the user’s screen, and the Web browser knows to run the JavaScript. The <script> tag is most often found within the <head> section of the HTML page, as in Listing 1.1, though you can, if you wish, have scripts in the <body> section. If you’re unfamiliar with these HTML concepts and you need more information about HTML, we suggest that you check out Elizabeth Castro’s HTML, XHTML, and CSS: Visual QuickStart Guide, Sixth Edition, also available from Peachpit Press.

Listing 1.1. This very simple script types “Hello, Cleveland!” into the browser window.


<!DOCTYPE html>
<html>
<head>
    <title>Barely a script at all</title>
    <script>
       window.onload = function() {
          document.getElementById ("myMessage").innerHTML = "Hello, Cleveland!";
       }
    </script>
</head>
<body>
<h1 id="myMessage">
</h1>
</body>
</html>


JavaScript Isn’t Java

Despite the names, JavaScript and Java have almost nothing to do with one another. Java is a full-featured programming language developed by Sun Microsystems and marketed by Oracle (since their purchase of Sun). With Java, a descendant of the C and C++ programming languages, programmers can create entire applications and control consumer electronic devices. Unlike other languages, Java promises cross-platform compatibility; that is, a programmer should be able to write one Java program that can then run on any kind of machine, whether that machine is running Windows, Mac OS X, or any of the different flavors of Unix. In practice, Java hasn’t always realized that dream, due in no small part to bickering between Sun and Microsoft as to the direction of the language. Microsoft got involved because it first wanted to integrate Java into Windows in its own way (a way that Sun said would make Java work one way on Windows, and another way on other machines, thereby defeating Java’s main purpose); then Microsoft dropped Sun’s Java from Windows altogether, after creating its own Java-like language, C#. After a flurry of lawsuits between the two companies (and a big settlement in favor of Sun), Microsoft removed its Java from Windows, and you can now install the latest version of Java for Windows (or Linux) at www.java.com/getjava/. Mac OS X comes with Java installed as part of the operating system.

Besides standalone applications, Java’s main use on the client side, that is, in the user’s browser, is to create applets, small programs that download over the Internet and run inside Web browsers. Because of Java’s cross-platform nature, these applets should run identically on any Java-enabled browser. In recent years, we’ve seen many Java applets for browsers replaced by Adobe Flash animations, which are generally easier to create than Java applets. In recent years, the increase of computer processing speeds and improved JavaScript implementations in browsers have further eroded Java’s use on the client side. However, Java has become a popular language for applications written for use on the server side.

You embed Java applets in your Web pages using the <object> HTML tag, with additional information specifying the applet. When the browser sees the <object> tag, it downloads the Java applet from the server, and the applet then runs in the area of the screen specified in the tag Image.

Image

Image This Java applet plays a mean game of checkers.

Where JavaScript Came From

If JavaScript isn’t related to Java, then why do they have such similar names? It’s another example of one of the computer industry’s most annoying traits: the triumph of marketing over substance.

Long ago, when Netscape added some basic scripting abilities to its Navigator Web browser, it originally called that scripting language LiveScript. Around the same time, Java was getting lots of press as the Next Big Thing In Computing. When Netscape revised Navigator to run Java applets in Navigator 2, it also renamed LiveScript to JavaScript, hoping that some of Java’s glitter would rub off. The mere fact that JavaScript and Java were very different programming languages didn’t stop Netscape’s marketing geniuses, and ever since then, writers like us have made good money explaining that JavaScript and Java are very different things. Come to think of it, maybe we should be thanking those marketers.

When Microsoft saw that JavaScript was becoming popular among Web developers, it realized that it would have to add some sort of scripting capabilities to Internet Explorer. It could have adopted JavaScript, but as is so often the case, Microsoft instead built its own language that works much like JavaScript but is not exactly the same. This Microsoft version of JavaScript is called JScript.

What JavaScript Can Do

There are many things that you can do with JavaScript to make your Web pages more interactive and provide your site’s users with a better, more exciting experience. JavaScript lets you create an active user interface, giving the users feedback as they navigate your pages. For example, you’ve probably seen sites that have buttons that highlight as you move the mouse pointer over them. That’s done with JavaScript, using a technique called a rollover Image.

Image

Image A rollover is an image that changes when you move the mouse pointer over it.

You can use JavaScript to make sure that your users enter valid information in forms, which can save your business time and money. If your forms require calculations, you can do them in JavaScript on the user’s machine without any server-side processing. That’s a distinction you should know: programs that run on the user’s machine are referred to as client-side programs; programs running on the server (including things called CGIs; more on them later) are called server-side programs.

With JavaScript, you have the ability to create customized Web pages, depending on actions that the user takes. Let’s say that you are running a travel site, and the user clicks Hawaii as a destination. You can have the latest Hawaii travel deals appear in a new window. JavaScript controls the browser, so you can open up new windows, display alert boxes, and put custom messages in the status bar of the browser window. Because JavaScript has a set of date and time features, you can generate clocks, calendars, and timestamp documents.

You can also use JavaScript to deal with forms, set cookies, build HTML pages on the fly, and create Web-based applications.

What JavaScript Can’t Do

JavaScript is a client-side language; that is, it is designed to do its work on your machine, not on the server. Because of this, JavaScript has some limitations built in, mostly for security reasons:

• JavaScript does not allow the writing of files on server machines. There are a number of ways in which this would be handy (such as storing page-hit counts or filled-out form data), but JavaScript isn’t allowed to do that. Instead, you’ll need to have a program on your server to handle and store this data. This can be, for example, a CGI (a program that runs on the server) written in a language such as Java, Perl, or PHP.

• JavaScript cannot close a window that it hasn’t opened. This is to avoid a situation where a site takes over your browser, closing windows from any other sites.

• JavaScript cannot read information from an opened Web page that came from another server. In other words, a Web page can’t read any information from other open windows and find out what else a surfer visiting the site is up to.

What Is Ajax?

The short answer is that it’s a way to create interactive Web applications. All right, now what does that mean? Let’s think about things that you might want to do with a Web site. For example, you might want to go out to dinner with your spouse. (If you don’t have a spouse, feel free to substitute “friend,” “relative,” or “pet” for “spouse” in the previous sentence. Though most people don’t go to dinner with their pets. But we digress.) So you want to know how to get from your place to that fabulous new restaurant downtown that everyone’s told you about. You decide to look up directions on a Web site that provides maps. You go to the site, type in the restaurant’s address, and the site shows you a map with the restaurant marked. This particular site shows you the map, with a border that you can click if you want to change the map view. You click a border, wait five to ten seconds or so for the map to redraw, and, if you want to change the view again, repeat. It’s a slow process and not very responsive to you. Wouldn’t it be better to just click the map and drag it in the direction you want, and the map view moves as you drag?

That’s the kind of dynamic responsiveness you can provide to your users with a Web application built with Ajax Image. There’s almost no waiting; the user is in control; and it allows you to create Web-based applications with the kind of user experience found on a traditional desktop application. Plus, it makes it a lot faster and easier to find out how to get from home to that great dinner.

Image

Image The Ajax-ified Google Maps allows a more fluid and responsive user experience.

Ajax is shorthand for Asynchronous JavaScript and XML, and was first coined in early 2005 by Jesse James Garrett, a Web developer and author. Strictly speaking, Ajax is just a small (although particularly popular) part of JavaScript. As commonly used, though, the term no longer refers to a technology by itself (like, say, Java or JavaScript).

In the larger scheme of things, what’s generally referred to as Ajax is the combination of these technologies:

• HTML

• CSS (Cascading Style Sheets)

• The DOM (Document Object Model) accessed using JavaScript

• XML or JSON, the data formats being transferred between the server and the client

• XMLHttpRequest to retrieve data from the server

Whew. That’s quite a list, especially if you don’t have much experience with JavaScript or other Web programming. But you shouldn’t worry; throughout this book, we’ll introduce each of these technologies. By the time you get to the Ajax parts, the pieces that make it up should be old hat.

The benefit to Ajax is that most of the processing for the application is happening within the user’s browser, and requests to the server for data are usually short. So with Ajax, you can give users the kind of rich applications that depend on Web-based data, without the performance penalty of older approaches, which required that the server send back entire pages of HTML in response to user actions.

Some companies have made huge investments in Ajax, notably Google, which has built several major Ajax applications, including Gmail (its Web-based email), Google Calendar, Google Docs, and Google Maps. Another big supporter of Ajax is Yahoo!, which uses Ajax to enhance its personalized My Yahoo! portal, the Yahoo! front page, Yahoo! Mail, and more. Both companies have made interfaces to their Web applications public, so that people can use them to make interesting new applications. For example, many people have created mashups for Google Maps, which take a map and overlay interesting, useful, or just wacky information on the map, such as the location of all Japanese restaurants or the filming locations for movies in the Los Angeles area.


Tip

For a nice listing of many Google Maps mashups, see Google Maps Mania (googlemapsmania.blogspot.com).


The Snap-Together Language

Here’s another buzzword that we should get out of the way: JavaScript is an object-oriented language. So what does that mean?

Objects

First, let’s think about objects. An object is some kind of a thing. A cat, a computer, and a bicycle are all objects Image in the physical world. To JavaScript, there are objects it deals with in Web browsers, such as windows and forms, and the elements of the form, such as buttons and check boxes Image.

Image

Image The cat object (this one’s name is Pixel).

Image

Image The buttons and check box are browser objects, which can be manipulated by JavaScript.

Because you can have more than one cat, or more than one window, it makes sense to give them names. While you could refer to your pets as Cat #1 and Cat #2, it’s a bad idea for two reasons: first, it’s easier to tell the cats apart if they have unique names, and second, it’s just plain impolite. In the same way, all the examples in this book will give objects their own unique names.


Tip

Be aware that scripts you might see on the Internet will refer to objects like window[0] and form[1]. This is poor style for the reasons given above, and you’ll find that it’s much easier for you to keep track of the different objects in your scripts if you give them names instead of numbers.



Tip

Some persnickety programmers will argue that JavaScript isn’t really object-oriented, but rather, that it’s actually object-based. For the purposes of this book, the two meanings are close enough that it makes no difference.


Properties

Objects have properties. A cat has fur, the computer has a keyboard, and the bicycle has wheels. In the JavaScript world, a document has a title, and a form can have a check box.

Changing a property of an object modifies that object, and the same property name can be a part of completely different objects. Let’s say that you have a property called empty. It’s okay to use empty wherever it applies, so you could say both that the cat’s tummy is empty and that the cat’s bowl is empty.

Note that the computer’s keyboard and the bicycle’s wheels aren’t only properties; they are also objects in their own right, which can have their own properties. So objects can have sub-objects.

Methods

The things that objects can do are called methods. Cats purr, computers crash, and bicycles roll. JavaScript objects also have methods: buttons click(), windows open(), and text can be selected(). The parentheses signal that we’re referring to a method, rather than a property.


Tip

It might help to think of objects and properties as nouns, and methods as verbs. The former are things, and the latter are actions that those things can do, or have done to them.


Putting the pieces together

You can put together objects, properties, and methods to get a better description of an object, or to describe a process. In JavaScript, these pieces are separated by periods (also known as dots, as in Internet addresses). This is called dot syntax. Here are some examples of objects and their properties written in this way:

bicycle.wheels

cat.paws.front.left

computer.drive.dvd

document.images.name

window.status

And here are some examples of objects and methods written in dot syntax:

cat.purr()

document.write()

forms.elements.radio.click()

Introducing the Document Object Model

On a Web page, the objects that make up the page (or document) are represented in a tree structure. You’ve seen this sort of thing before when building HTML pages; the top level of the page is contained in the <html> tag, and inside that you’ll find the <head> and <body> tags, with other tags within each of those, and so on. Some browsers can show you representations of this tree structure, as in Image. JavaScript considers each of the items in the document tree to be objects, and you can use JavaScript to manipulate those objects. The representation of the objects within the document is called the Document Object Model (DOM).

Image

Image You can see a document’s tree structure using the DOM Inspector, which is an add-on for Firefox (shown here); there are similar features in Safari and Internet Explorer.

Each of the objects on the tree is also called a node of the tree. We can use JavaScript to modify any aspect of the tree, including adding, accessing, changing, and deleting nodes on the tree. Each object on the tree is a node. If the node contains an HTML tag, it’s referred to as an element node. Otherwise, it’s referred to as a text node. Of course, element nodes can contain text nodes. That’s all you need to know about the DOM and nodes for now; you’ll learn more about them throughout the book, especially in Chapter 10.

Handling Events

Events are actions that the user performs while visiting your page. Submitting a form and moving a mouse over an image are two examples of events.

JavaScript deals with events using commands called event handlers. An action by the user on the page triggers an event handler in your script. The 12 most common JavaScript event handlers are listed in Table 1.1. We deal with other, more advanced event handlers in Chapter 8.

Table 1.1. Event Handlers

Image

For example, let’s say that our cat handles the event onpetting by performing the actions purr and stretch.

In JavaScript, if the user clicks a button, the onclick event handler takes note of the action and performs whatever duties it was assigned.

When you write a script, you don’t have to anticipate every possible action that the user might take, just the ones where you want something special to occur. For instance, your page will load just fine without an onload event handler. But you need to use the onload command if you want to trigger a script as soon as the page loads.

Values and Variables

In JavaScript, a piece of information is a value. There are different kinds of values; the kind you’re most familiar with are numbers. A string value is characters—such as a word or words—enclosed in quotes. Other kinds of JavaScript values are listed in Table 1.2.

Table 1.2. Value Types

Image

Variables contain values. For example, the variable myName is assigned the string “Dori”. Another way to write this is myName = "Dori". The equals sign can be read as “is set to.” In other words, the variable myName now contains the value “Dori”.


Tip

JavaScript is case sensitive. This means that myname is not the same as myName, and neither is the same as MyName.



Tip

Variable names cannot contain spaces or other punctuation, or start with a digit. They also can’t be one of the JavaScript reserved words. See Appendix B for a list of JavaScript reserved words.


Operators

Operators are the symbols used to work with variables. You’re already familiar with operators from simple arithmetic; plus and minus are operators. See Table 1.3 for a list of the most common operators.

Table 1.3. Operators

Image


Tip

While both x++ and ++x add one to x, they are not identical; the former increments x after the assignment is complete, and the latter before. For example, if x is 5, y=x++ results in y set to 5 and x set to 6, while y=++x results in both x and y set to 6. The operator −- (minus sign) works similarly.



Tip

If you mix numeric and string values when adding two values together, the result is a string. For example, "cat" + 5 results in "cat5".


Assignments and Comparisons

When you put a value into a variable, you are assigning that value to the variable, and you use an assignment operator to do the job. For example, you use the equals operator to make an assignment, such as hisName = "Tom". There are a whole set of assignment operators, as listed in Table 1.4.

Table 1.4. Assignments

Image

Other than the equals sign, the other assignment operators serve as shortcuts for modifying the value of variables. For example, a shorter way to say x=x+5 is to say x+=5. For the most part, we’ve used the longer version in this book for clarity’s sake.

Comparisons

You’ll often want to compare the value of one variable with another, or the value of a variable against a literal value (i.e., a value typed into the expression). For example, you might want to compare the value of the day of the week to “Tuesday”, and you can do this by checking if todaysDate == "Tuesday" (note the two equals signs). A list of comparisons is in Table 1.5.

Table 1.5. Comparisons

Image


Tip

If you are comparing strings, be aware that “a” is greater than “A” and that “abracadabra” is less than “be”.


Writing JavaScript-Friendly HTML

Because you’ll be using JavaScript to manipulate the objects within a document, you want to write your HTML in a way that can be easily used by your scripts. That basically means writing modern, standards-compliant HTML and using CSS to separate the document’s structure from its presentation.

When we say modern HTML, we don’t just mean documents that pass W3C validation using the Web tool at validator.w3.org. We also recommend thinking ahead to what you are likely to do with a page and adding appropriate tags and attributes that will make it easy to access objects with JavaScript. What sort of markup, you wonder? Glad you asked.

Structure, presentation, and behavior

CSS (Cascading Style Sheets) is a standard layout language for the Web that controls typography, colors, and the size and placement of elements and images. Your HTML documents should have external style sheets defining the styles used within the document. Your JavaScript should also be in an external document, one that contains only JavaScript code.

When split up this way, your sites will contain three types of text files:

• HTML: contains the content and structure of the page

• CSS: controls the appearance and presentation of the page

• JavaScript: controls the behavior of the page

When you do this, it becomes straightforward to make changes to your site—even changes with site-wide effects.

Divs and spans

If you’re used to the classic style of HTML, where you threw everything into tables and played with spacer GIFs until it all fell into more-or-less the layout you wanted, some of this will be new to you—so here’s a quick overview to bring you up to date.

Modern HTML and XHTML contain two tags that are finally getting the attention they deserve: <div> and <span>. They’re used to break up your content into semantic chunks, that is, chunks that have a similar meaning. Things inside a single table cell or paragraph may or may not have anything in common, but the content within each <div> and <span> should.

Why use one over the other? A <div> is a block-level element, that is, there’s a physical break between it and the elements above and below it. A <span> isn’t block-level; instead, it’s inline, so you can apply it to, for instance, a single phrase within a sentence.

We’re not saying that you need to junk everything you’ve ever learned about HTML—far from it! But add these two tags to your toolkit of solutions, and you’ll be surprised how often you use them.

Classes and ids

Inside your HTML document, you’ll mark up your content by breaking it down into those meaningful chunks. From there, you’ll still need to identify those pieces of content where you want to change their presentation or behavior. For that, you’ll primarily use two attributes: class and id. These attributes can be used by both CSS and JavaScript; a CSS style sheet uses those attributes as part of rules to define the appearance of a page, and the JavaScript file can use those attributes in code that affects the behavior of elements on the page.

A class identifies an element that you may want to use more than once. For example, let’s say that you’re creating a page for a movie theater. You can define a class for the movie titles, specifying that the titles should be 14 pixels, bold, and dark blue.

.movieTitle {
  font: bold 14px;
  color: #000099;
}

You should then wrap each movie title on your page with a tag specifying the class of the title style, like so:

<p>We're currently showing <span class="movieTitle"> The Aviator</span> and <span class="movieTitle"> The Outlaw</span>.</p>

• An id identifies an element that is unique to that document. For example, if you only use the name of the movie theater once on your page, you can create a style rule using an id to define how the theater’s name will look, like this:

#theaterName {
  font: bold 28px;
  color: #FF0000;
}

Then, when it’s time to show the name of the theater, all you do is add that id attribute to the tag to get the effect:

<h1 id="theaterName">The Raven Theater Presents:</h1>

What goes for CSS in the above examples also applies to JavaScript. Once we’ve assigned classes and ids to our divs and spans (and to any other elements as well), we can then modify those elements: not just their appearance with CSS, but also their behavior with JavaScript. And that’s a topic that will take up the rest of this book.


Tip

Having trouble remembering when to use # versus . in your CSS because you can’t recall which one goes with class and which with id? Here’s our method: an id can be on any given page one time, and only one time. One is a number, and the hash symbol (#) is also called a number sign—so it’s the one that goes with id.


What Tools to Use?

Since JavaScript is just plain text, you could use almost any kind of text editor. You could even use a word processor like Microsoft Word, though you would always have to make sure that Word saved the file as Text Only, instead of in its native file format. HTML, JavaScript, and CSS files must always be in plain text format so Web servers can understand them.

You’re better off using a program that has plain text as its standard format. On Windows, many people get away with using Notepad Image. On the Mac, you can use TextEdit, though a favorite of professionals is BBEdit, by Bare Bones Software Image. On Unix machines, Emacs is one of the best text editors available. No matter what program you use, don’t forget to save your plain text files with the proper extension (.html, .css, or .js) so that things will go smoothly when you upload the file to a Web server.

Image

Image Notepad on Windows 7.

Image

Image BBEdit on Mac OS X.

You can also use some of the WYSIWYG (What You See Is What You Get) HTML editors available, such as Dreamweaver. Just switch to their HTML Source mode and script away.


Tip

If you’re a Mac user, try TextWrangler, also from the Bare Bones folks (www.barebones.com). It’s not as full-featured as BBEdit, but it has a big point in its favor: it’s free.



Tip

If you are interested in learning more about using the code tools in Dreamweaver, we recommend Dreamweaver CS5: Visual QuickStart Guide, written by, uh, us.


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

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