Section 14.2. JavaScript 101


14.2. JavaScript 101

Now that you've learned a bit about JavaScript and why it exists, it's time to dive right in and start creating your first real script.

14.2.1. The <script> Tag

Every script starts with a <script> block that you slot somewhere into an HTML document. Really, you have only two options:

  • The <body> section . Put scripts in the <body> section that you want to run right away, when the browser's in the process of reading (and displaying) your page. The browser launches your script as soon as the browser reaches the script in the HTML document. This means if you put your script at the beginning of the <body> section, the script gets fired up before the rest of the HTML is displayed in the browser.


    Tip: Usually, JavaScript fans put their scripts at the end of the <body> section. That way, you avoid errors that might occur if you use a script that relies on another part of the page, and the browser hasn't read that other section yet. Because browsers read an entire page quite quickly, these scripts execute almost immediately.
  • The <head> section . If you place an ordinary script in the <head> section, it runs immediately, before the browser has processed any part of the HTML for the page. However, it's more common to use the <head> sections for scripts that contain functions (see Section 14.2.3). Functions don't run immediatelyinstead, they're summoned when some kind of action happens on the page (for example, when the Web surfer moves her mouse).


Note: You can place as many <script> blocks in a Web page as you want.

A typical script block consists of a series of programming instructions. To get a handle on how these instructions work, consider the following example, which causes the browser to display a JavaScript alert box.

 <html> <head> <title>JavaScript Test</title> </head> <body> <h1>You Will Be Wowed</h1> <p>This page uses JavaScript.</p>  <script type="text/javascript"> alert("Welcome, JavaScript coder.") </script>  </body> </html> 

This script pops up a window with a message, as shown in Figure 14-2. When you click OK, the message disappears, and it's back to life as usual for your Web page.

Figure 14-2. Because the script tag is positioned at the end of the document, the browser displays all the HTML first and then pops up this alert box. If you put the script tag at the beginning of the <body> section (or in the <head> section), the page would still be blank when the alert box appears. The browser would then wait until you clicked OK to read the rest of the HTML page and display its contents.


You're probably wondering exactly how this script works its magic. When the browser processes the script, it 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 the built-in JavaScript function named alert . A function is a programming routine consisting of one or more lines of code that performs a certain task. JavaScript offers many built-in functions, and you can build your own.

The alert() function requires one piece of information, or an argument , in programmer-speak. In this case, that piece of information is the text you want to show in the alert box. If you were supplying an ordinary number, you could type it in as isthat is, you'd just write in the number. However, text poses a bit more of a problem, because there's no way for the browser to tell where the text starts and stops. To handle this problem in JavaScript, you must put your text inside single apostrophe quotes (') or double quotation marks ("), as in this example.


Note: In programmer-speak, a distinct piece of text that's used in a program is called a string ; "a," "The friendly fox," and "Rumpelstiltskin" all qualify as strings.

That's it. All this simple script does is call the 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 of summoning a function into action.) The alert() function does the rest, popping up the correct- sized window and waiting for the surfer to click OK.


Note: In order to write this script, you need to know that there's an alert() function ready for you to usea 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 in the following ways:

  • 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 the Web page is shown (by changing the position of the <script> block).

It's not much to keep you occupied, but it does demonstrate how easy it is to get started using and changing a simple script.

14.2.1.1. Scripts and really, really old browsers

Sometimes, scripts are written with the comment markers shown here:

 <script type="text/javascript">  <!--  alert("Welcome, JavaScript coder.")  //-->  </script> 

Placing the comment markers like this hides the script from Paleolithic browsers like Netscape 2, which don't understand scripts and are dimwitted enough to display the actual script text in the browser window. The chances of running into one of these beasties today is quite rare, so many JavaScript coders don't even bother with this extra step.

UP TO SPEED
Spaces and Line Breaks in JavaScript

JavaScript 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 C and Java.

If you don't want to put more than one code statement on the same line, you don't need the semicolons. However, you're still free to add them if you want, at the end of each line. In fact, if you download a script from the Web, you just might find these optional semicolons, which is often a tip-off that a C or Java programmer wrote the script.


Even if you aren't expecting really old browsers to come by your Web site, you might want to use the <noscript> tag. This tag defines some alternate content that's used by browsers that understand the meaning of the <script> tag, but have JavaScript switched off. It's also used for browsers that don't support the script language you're using. For example, most non-IE browsers don't support VBScript, a scripting language based on Visual Basic.

You place the <noscript> tag immediately after the <script> tag. Here's an example that shows a paragraph of text in the page when JavaScript support is lacking:

 <script type="text/javascript"> alert("Welcome, JavaScript coder.") </script> <noscript> <p>Welcome, non-JavaScript-enabled browser.</p> </noscript> 

14.2.2. Variables

Every programming language includes the concept of variables , which are temporary storage containers where you can keep track of 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 JavaScripts, and they're a powerful tool in any programmer's arsenal.

14.2.2.1. 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 ). Here's an example that creates a variable named myMessage :

 var myMessage 

To put information into a variable, you use the equal sign (=), which copies the data on the right side of the equal sign into the variable on its left. Here's an example that puts some text into myMessage.

 myMessage = "Everybody loves variables" 

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

 myNumber = 27.3 


Note: JavaScript variables are case-sensitive, which means a variable named myMessage isn't the same as MyMessage. If you try to use them interchangeably, you'll wind up with a scripting error (if your browser is nice) or a bizarre mistake in the page (which is usually what happens).

Often, you'll want to create a variable and fill it with some useful content in the same step. JavaScript lets you do perform this maneuver by placing the equal sign immediately after the variable name when you declare it:

 var myMessage = "Everybody loves variables" 

To make matters a little confusing, JavaScript lets you use variables that you haven't 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.

14.2.2.2. Modifying variables

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

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

These calculations follow the standard order of operations (parentheses, then addition and subtraction, then multiplication and division). 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, it's the plus (+) operator that you use:

 var firstName = "Sarah" var lastName = "Smithers" var fullName = firstName + " " + lastName 

Now the fullName variable holds the text "Sarah Smithers".

14.2.2.3. 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 the Web page. Each line of script code is numbered to make it easy to reference.

 <html> <head> <title>JavaScript Test</title> </head> <body> <h1>What Day Is It?</h1> <p>This page uses JavaScript.</p> <p>  <script type="text/javascript">  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 new variable named currentDate . It fills the currentDate variable with a new Date object. You'll know an object is being created when you see the keyword new . (You'll learn more about objects on Section 14.3; for now, it's enough to know that objects 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 , and fills it with a generic welcome message.

  3. This line adds some new text to the end of the message. The new text comes from the currentDate object. The tricky part is understanding that the currentDate object comes with a built-in toDateString() function that converts the date information into a piece of text suitable for displaying in the browser (see Figure 14-3). Once again, this is the kind of detail you can only pick up by studying a good JavaScript reference.

    Figure 14-3. Some HTML editors will help you out when you write JavaScript code. For example, FrontPage shows a drop-down menu that shows you all the functions an object provides. Although this probably isn't enough for you to figure out how to use the Date object for the first time, it's a great way to refresh your memory later on.


  4. This line uses the document object, which has a function named write() . The write() function copies a piece of text into the page at the current location. The final result is a page that shows your welcome message (see Figure 14-4).

Scripts can get much more complex than this. For example, they can use loops to repeat a single action several times, or use conditional logic to make decisions. You'll see examples of some of these techniques in this chapter, but you won't get a blow-by-blow exploration of the JavaScript languagein fact, that would require a small book of its own. If you want to learn more, check out the box "Becoming a JavaScript Guru."

14.2.3. Functions

So far, you've seen simple scripts that use only a few lines of code. More realistic JavaScript scripts can take 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 use custom functions .

A function is a series of code instructions that you group together and give a name. In a way, functions are sort of like miniature programs, because they can perform a series of operations. The neat thing about functions is that you only need to create them once, and then you can reuse them anywhere .

Figure 14-4. The document.write() command inserts your text directly into the page, wherever the script block is positioned. In this case, it shows the current date.


14.2.3.1. Declaring a function

To create a JavaScript function, start by deciding what your function is going to do (like show an alert message) and then choose a suitable name (like ShowAlertBox ). As with most things in the programming world, the function name can't have any spaces or special characters.

Armed with this information, you're ready to put a <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 type="text/javascript">   function ShowAlertBox() { alert("I'm a function.")   } </script> 

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

Every function declaration starts with the word function , which tells JavaScript what you're up to.

  function  

Next is the name of your function and then two parentheses. The parentheses can be used to get extra information to feed into your function, as you'll see on Section 14.2.3.3.

 function  ShowAlertBox()  

At this point, you've finished declaring the function. All that remains is to put the code you want inside that function. To do this, you need the funny curly braces shown above. The { brace indicates the start of your function code and the } brace indicates the end. In between, you can put as many code statements as you want.

One tricky part of function writing is the fact that JavaScript is notoriously loose about line breaks. That means you can create an equivalent JavaScript function that moves the curly brace down a line, and looks like this:

 <script type="text/javascript">   function ShowAlertBox() { alert("I'm a function.")   } </script> 

But don't worryboth functions work exactly the same.


Tip: You can put as many functions as you want in a single <script> block. Just add them one after the other.
POWER USERS' CLINIC
Becoming a JavaScript Guru

JavaScript requires some basic programming skills. However, it's fairly forgiving . Even non- geeks can learn to use JavaScript to create their own wildly customized programs (with the right motivation).

If you've decided that you're not satisfied in using other people's JavaScripts, and you want to be able to create your own, it's time to learn more. And although in-depth JavaScript programming is beyond the scope of this book, there are plenty of great resources to get you started.

If you're happy learning from the Web, there's no shortage of tutorials. Three great places to start are www.w3schools.com/js, www.echoecho.com/javascript.htm, and www.htmlgoodies.com/primers/jsp. If you want a more hardcore approach, you may be interested in JavaScript & DHTML Cookbook (O'Reilly), which provides a whack of JavaScript examples, or JavaScript: The Definitive Guide (O'Reilly), which is the 900-page final word on the subject (although not for the faint of heart).


14.2.3.2. Calling a function

Creating a function is only half the battle. On their own, functions don't do anything. It's up to you to call the function somewhere else 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, the browser 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 shows the alert message three times in a row to really hassle your visitors :

 <script type="text/javascript"> ShowAlert() ShowAlert() ShowAlert() </script> 

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

14.2.3.3. Functions that receive information

The ShowAlertBox() function is beautifully simple. You simply call it, and it displays an alert box with the built-in message. Most functions don't work this easily. That's because 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 show a welcome message with some standard information (like the current date). However, say you want to have the flexibility to change part of this message by supplying your own witty words each time you call the function. In this case, you need a way to call a function and supply a text string with your message.

To solve this problem, you can create a ShowAlertBox() function that accepts a single argument. This argument represents the customized piece of information you want to incorporate into your greeting. You choose a name for it, and place it in between the parentheses after the function name, like so:

 function ShowAlertBox(  customMessage  ) { } 

There's no limit to how many pieces of information a function can accept. You just need to separate each argument with a comma. Here's an example with three arguments:

 function ShowAlertBox(messageLine1, messageLine2, messageLine3) { } 

The following example shows the finished ShowAlertBox() function. It accepts a single argument named customMessage, and uses it to customize the text that's shown in the alert box:

 <script type="text/javascript"> 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 helpful 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. The browser ignores them.

  • To put line breaks into an alert box, you need to use the code \n in your strings (lines 7, 8, and 9). Each \n is equivalent to one line break. (This rule is for message boxes only. When writing HTML, you need to add the <br> tag to create a line break.)

  • To build the text for the fullMessage variable (lines 7 to 10), the code uses a shortcut with 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 that's 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. You just need to remember that when you call the function, you must supply the same number of arguments as you defined for the function, separating each one with a comma. In the case of ShowAlertBox(), you only need to supply a single value for the customMessage variable. Here's an example:

 <script type="text/javascript"> ShowAlertBox("This Web page includes JavaScript functions.") </script> 

Figure 14-5 shows the result of this script.

Figure 14-5. This message is built out of several pieces of text, one of which is supplied as an argument.


14.2.3.4. Functions that return information

Arguments let you send information to a function. You can also create functions that send some information back to the script code that called them. The trick to doing this is the return command, which you should place right at the end of your function. The return command ends the function immediately, and spits out whatever information you want your function to generate.

Of course, a sophisticated function can accept and return information. For example, here's a function that multiplies two numbers (supplied as arguments) and returns the result to anyone who's interested:

 <script type="text/javascript"> function MultiplyNumbers(numberA, numberB) { return numberA * numberB } </script> 

Here's how you can use the function elsewhere in your Web page:

 <p>The product of 3202 and 23405 is <script type="text/javascript"> var product =  MultiplyNumbers(3202, 23405)  document.write(product) </script> </p> 

This displays the following text in a paragraph on your page:

 The product of 3202 and 23405 is 74942810 

To use a typical script from the Web, you'll need to copy one or more functions into your page. These functions are 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'll be able to wade through the code to get a basic understanding of what's taking place (or at least pinpoint where the action is going down).

14.2.4. External Script Files

Reusing scripts inside a Web page is neat, but did you know you can share scripts between individual pages and even different Web sites? The trick is to put your script into an external file and then link to it. This procedure is similar to the external style sheet linking you learned about back in Chapter 6.

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

Script files are always plain text files. Usually, they have the extension .js (for JavaScript). Inside the script file, you put all your code, but you don't include the <script> tags. For example, you could create a JavaScript file named ShowAlert.js and add this code to it:

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

Now save the file, and place it in the same folder as your Web page. In your Web page, you define a script block, but you don't supply any code. Instead, you add the src attribute and indicate the script file you're linking to:

 <script type="text/javascript"  src="ShowAlert.js"  > </script> 

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

 <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 type="text/javascript" src="ShowAlert.js"> </script> </head> <body> <!-- Test out one of the functions. --> <script type="text/javascript"> ShowAlertBox() </script> </body> </html> 

There's no difference in the ways that embedded and external scripts work. However, placing your scripts in separate files helps keep your Web site organized and makes it easy to reuse scripts across several pages. In fact, you can even link to JavaScript functions on another Web sitethe only difference is the src attribute in the <script> block needs to point to a full URL (like http://SuperScriptSite.com/ShowAlert.js ) instead of just a file name.


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


Creating Web Sites. The Missing Manual
Creating Web Sites: The Missing Manual
ISBN: B0057DA53M
EAN: N/A
Year: 2003
Pages: 135

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net