2 Creating Simple Scripts

wax ka badal

Tools for Scripting

wax ka badal

Unlike many programming languages, you won't need any special software to create JavaScript scripts. In fact, you probably already have everything you need.

Text Editors

wax ka badal

The first tool you'll need to work with JavaScript is a text editor. JavaScript scripts are stored in simple text files, usually as part of HTML documents. Any editor that can store ASCII text files will work.

You can choose from a wide range of editors, from simple text editors to word processors. If you don't have a favorite editor already, a simple editor is most likely included with your computer. For Windows computers, the Notepad accessory will work just fine.

Watch Out
If you use a word processor to create JavaScript programs, be sure you save the files as ASCII text rather than as word processing documents. Otherwise, the browser might not recognize them.

A variety of dedicated HTML editors is also available and will work with JavaScript. In fact, many include features specifically for JavaScript, for example, color-coding the various JavaScript statements to indicate their purposes, or even creating simple scripts automatically.

For Windows computers, here are a few recommended editors:

  • HomeSite An excellent HTML editor that includes JavaScript support. HomeSite is included as part of Adobe Dreamweaver and is also available separately.
  • Microsoft FrontPage 2003 Microsoft's visual HTML editor. The Script Builder component enables you to easily create simple scripts.
  • TextPad A powerful text editor that includes a number of features missing from Notepad. TextPad's view of a JavaScript document is shown in Figure 2.1.

The following editors are available for both Windows and Macintosh:

  • Adobe Dreamweaver A visually oriented editor that works with HTML, JavaScript, and Macromedia's Flash plug-in.
  • Adobe GoLive A visual and HTML editor that also includes features for designing and organizing the structure of large sites.

Additionally for the Macintosh, BBEdit, TextWrangler, and Alpha are good HTML editors that you can use to create web pages and scripts.

By the Way
Appendix B, "Tools for JavaScript Developers," includes web addresses to download these and other HTML and JavaScript editors.

You'll need two other things to work with JavaScript: a web browser and a computer to run it on. Because this book covers new features introduced up to JavaScript 1.5 and the latest W3C DOM, I recommend that you use the latest version of Mozilla Firefox or Microsoft Internet Explorer. See the Mozilla (http:// www.mozilla.com) or Microsoft (http:// www.microsoft.com) website to download a copy.

At a minimum, you should have Firefox 1.0, Netscape 7.0, or Internet Explorer 6.0 or later. Although Netscape 4.x and Internet Explorer 4 will run many of the scripts in this book, they don't support a lot of the latest features you'll learn about.

You can choose whichever browser you like for your web browsing, but for developing JavaScript you should have more than one browser, at a minimum, Firefox and Internet Explorer. This will allow you to test your scripts in the common browsers users will employ on your site.

By the Way
If you plan on making your scripts available over the Internet, you'll also need a web server, or access to one. However, you can use most of the JavaScript examples in this book directly from your computer's hard disk.

Displaying Time with JavaScript

wax ka badal

One common and easy use for JavaScript is to display dates and times. Because JavaScript runs on the browser, the times it displays will be in the user's current time zone. However, you can also use JavaScript to calculate "universal" (UTC) time.

By the Way
UTC stands for Universal Time (Coordinated), and is the atomic time standard based on the old GMT (Greenwich Mean Time) standard. This is the time at the Prime Meridian, which runs through Greenwich, London, England.

As a basic introduction to JavaScript, you will now create a simple script that displays the current time and the UTC time within a web page.

Beginning the Script

wax ka badal

Your script, like most JavaScript programs, begins with the HTML <script> tag. As you learned in Hour 1, you use the <script> and </script> tags to enclose a script within the HTML document.

Watch Out
Remember to include only valid JavaScript statements between the starting and ending <script> tags. If the browser finds anything but valid JavaScript statements within the <script> tags, it will display a JavaScript error message.

To begin creating the script, open your favorite text editor and type the beginning and ending <script> tags as shown.

<script LANGUAGE="JavaScript" type="text/javascript">
</script>

Because this script does not use any of the new features of JavaScript 1.1 or later, you won't need to specify a version number in the <script> tag. This script should work with all browsers going back to Netscape 2.0 or Internet Explorer 3.0.

Adding JavaScript Statements

wax ka badal

Your script now needs to determine the local and UTC times, and then display them to the browser. Fortunately, all of the hard parts, such as converting between date formats, are built in to the JavaScript interpreter.

Storing Data in Variables

wax ka badal

To begin the script, you will use a variable to store the current date. You will learn more about variables in Hour 5, "Using Variables, Strings, and Arrays." A variable is a container that can hold a value, a number, some text, or in this case, a date.

To start writing the script, add the following line after the first <script> tag. Be sure to use the same combination of capital and lowercase letters in your version because JavaScript commands and variable names are case sensitive.

now = new Date();

This statement creates a variable called now and stores the current date and time in it. This statement and the others you will use in this script use JavaScript's built-in Date object, which enables you to conveniently handle dates and times. You'll learn more about working with dates in Hour 8, "Using Built-in Functions and Libraries."

By the Way
Notice the semicolon at the end of the previous statement. This tells the browser that it has reached the end of a statement. Semicolons are optional, but using them helps you avoid some common errors. We'll use them throughout this book for clarity.

Calculating the Results

wax ka badal

Internally, JavaScript stores dates as the number of milliseconds since January 1, 1970. Fortunately, JavaScript includes a number of functions to convert dates and times in various ways, so you don't have to figure out how to convert milliseconds to day, date, and time.

To continue your script, add the following two statements before the final </script> tag:

localtime = now.toString();
utctime = now.toUTCString();

These statements create two new variables: localtime, containing the current time and date in a nice readable format, and utctime, containing the UTC equivalent.

By the Way

wax ka badal

The localtime and utctime variables store a piece of text, such as January 1, 2001 12:00 PM. In programming parlance, a piece of text is called a string. You will learn more about strings in Hour 5.

Creating Output

wax ka badal

You now have two variables, localtime and utctime, which contain the results we want from our script. Of course, these variables don't do us much good unless we can see them. JavaScript includes a number of ways to display information, and one of the simplest is the document.write statement.

The document.write statement displays a text string, a number, or anything else you throw at it. Because your JavaScript program will be used within a web page, the output will be displayed as part of the page. To display the result, add these statements before the final </script> tag:

 document.write("<b>Local time:</b> " + localtime + "<br>");
 document.write("<b>UTC time:</b> " + utctime);

These statements tell the browser to add some text to the web page containing your script. The output will include some brief strings introducing the results, and the contents of the localtime and utctime variables.

Notice the HTML tags, such as <b> , within the quotation marks, because JavaScript's output appears within a web page, it needs to be formatted using HTML. The <br> tag in the first line ensures that the two times will be displayed on separate lines.

By the Way
Notice the plus signs (+) used between the text and variables in the previous statements. In this case, it tells the browser to combine the values into one string of text. If you use the plus sign between two numbers, they are added together.

Adding the Script to a Web Page

wax ka badal

You should now have a complete script that calculates a result and displays it. Your listing should match Listing 2.1.

Listing 2.1. The Complete Date and Time Script
<script language="JavaScript" type="text/javascript">
now = new Date();
localtime = now.toString();
utctime = now.toUTCString();
document.write("<b>Local time:</b> " + localtime + "<BR>");
document.write("<b>UTC time:</b> " + utctime);
</script>

To use your script, you'll need to add it to an HTML document. In its most basic form, the HTML document should include opening and closing <html> tags, <head> tags, and <body> tags.

If you add these tags to the document containing your script along with a descriptive heading, you should end up with something like Listing 2.2.

Listing 2.2. The Date and Time Script in an HTML Document
<html>
<head><title>Displaying Times and Dates</title></head>
<body>
<h1>Current Date and Time</h1>
<p>
<script language="JavaScript" type="text/javascript">
now = new Date();
localtime = now.toString();
utctime = now.toUTCString();
document.write("<b>Local time:</b> " + localtime + "<BR>");
document.write("<b>UTC time:</b> " + utctime);
</script>
</p>
</body>
</html>

Now that you have a complete HTML document, save it with the .htm or .html extension.

By the Way
Notepad and other Windows text editors might try to be helpful and add the .txt extension to your script. Be sure your saved file has the correct extension.

Testing the Script

wax ka badal

To test your script, you simply need to load the HTML document you created in a web browser. Start Netscape or Internet Explorer and select Open from the File menu. Click the Choose File or Browse button, and then find your HTML file. After you've selected it, click the Open button to view the page.

If you typed the script correctly, your browser should display the result of the script, as shown in Figure 2.2. (Of course, your result won't be the same as mine, but it should be the same as the setting of your computer's clock.)

A note about Internet Explorer 6.0 and above: Depending on your security settings, the script might not execute, and a yellow highlighted bar on the top of the browser might display a security warning. In this case, click the yellow bar and select Allow Blocked Content to allow your script to run. (This happens because the default security settings allow JavaScript in online documents, but not in local files.)

Did you Know?
You can download the HTML document for this hour from this book's website. If the version you type doesn't work, try downloading the online version.

Modifying the Script

wax ka badal

Although the current script does indeed display the current date and time, its display isn't nearly as attractive as the clock on your wall or desk. To remedy that, you can use some additional JavaScript features and a bit of HTML to display a large clock.

To display a large clock, we need the hours, minutes, and seconds in separate variables. Once again, JavaScript has built-in functions to do most of the work:

hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();

These statements load the hours, mins, and secs variables with the components of the time using JavaScript's built-in date functions.

After the hours, minutes, and seconds are in separate variables, you can create document.write statements to display them:

document.write("<h1>");
document.write(hours + ":" + mins + ":" + secs);
document.write("</h1>");

The first statement displays an HTML <h1> header tag to display the clock in a large typeface. The second statement displays the hours, mins, and secs variables, separated by colons, and the third adds the closing </h1> tag.

You can add the preceding statements to the original date and time script to add the large clock display. Listing 2.3 shows the complete modified version of the script.

<html>
<head><title>Displaying Times and Dates</title></head>
<body>

<h1>Current Date and Time</h1>
<p>
<script language="JavaScript">
now = new Date();
localtime = now.toString();
utctime = now.toUTCString();
document.write("<b>Local time:</b> " + localtime + "<BR>");
document.write("<b>UTC time:</b> " + utctime);
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write("<h1>");
document.write(hours + ":" + mins + ":" + secs);
document.write("</h1>");
</script>
</p>
</body>
</html>

Now that you have modified the script, save the HTML file and open the modified file in your browser. If you left the browser running, you can simply use the Reload button to load the new version of the script. Try it and verify that the same time is displayed in both the upper portion of the window and the new large clock.

By the Way
The time formatting produced by this script isn't perfect: Hours after noon are in 24-hour time, and there are no leading zeroes, so 12:04 is displayed as 12:4. See Hour 8, "Using Built-in Functions and Libraries," for solutions to these issues.

Dealing with JavaScript Errors

wax ka badal

As you develop more complex JavaScript applications, you're going to run into errors from time to time. JavaScript errors are usually caused by mistyped JavaScript statements.

To see an example of a JavaScript error message, modify the statement you added in the previous section. We'll use a common error: omitting one of the parentheses. Change the last document.write statement in Listing 2.3 to read

document.write("</h1>";

Save your HTML document again and load the document into the browser. Depending on the browser version you're using, one of two things will happen: Either an error message will be displayed, or the script will simply fail to execute.

If an error message is displayed, you're halfway to fixing the problem by adding the missing parenthesis. If no error was displayed, you should configure your browser to display error messages so that you can diagnose future problems:

In Netscape or Firefox, type javascript: into the browser's Location field to display the JavaScript Console. In Firefox, you can also select Tools, JavaScript Console from the menu. The console is shown in Figure 2.4, displaying the error message you created in this example.

In Internet Explorer, select Tools, Internet Options. On the Advanced page, uncheck the Disable Script Debugging box and check the Display a Notification About Every Script Error box. (If this is disabled, a yellow icon in the status bar will still notify you of errors.)

By the Way
Notice the field at the top of the JavaScript Console. This enables you to type a JavaScript statement, which will be executed immediately. This is a handy way to test JavaScript's features.

The error we get in this case is missing ) after argument list (Firefox) or Expected ')' (Internet Explorer), which turns out to be exactly the problem. Be warned, however, that error messages aren't always this enlightening.

While Internet Explorer displays error dialog boxes for each error, Firefox's JavaScript Console displays a single list of errors and allows you to test commands. For this reason, you might find it useful to install Firefox for debugging and testing JavaScript, even if Internet Explorer is your primary browser.

Did you Know?
As you develop larger JavaScript applications, finding and fixing errors becomes more important. You'll learn more about dealing with JavaScript errors in Hour 16, "Debugging JavaScript Applications."

Try It Yourself Using a Separate JavaScript File

wax ka badal

Although simple scripts like this one can be embedded in an HTML file, as in the previous example, it's good practice to separate the HTML and JavaScript by using a separate JavaScript file. This has a few advantages:

Browsers with JavaScript disabled, or older browsers that don't support it, will ignore the script.

When multiple pages on your site use the same script, the browser only has to load the JavaScript file once, and use a cached copy on other pages.

It's easier to maintain the HTML and JavaScript code when they're separated, especially if different people are working on the design and the scripting.

We'll also be using separate JavaScript files for most of the examples in this book, so you should be familiar with this technique.

To use a separate JavaScript file with the date and time example, you will need two files. A quick way to create them is to save the combined HTML/JavaScript file in Listing 2.3 to two files, and then edit them.

The first file, datetime.html, will be the HTML file. Remove everything between the <script> tags, and add the src="datetime.js" attribute to the opening <script> tag. The resulting file is shown in Listing 2.4.

Listing 2.4. HTML File for the Date and Time Script (datetime.html)

<html>
<head><title>Displaying Times and Dates</title></head>
<body>
<h1>Current Date and Time</h1>
<p>
<script language="JavaScript" type="text/javascript"
 src = "datetime.js">
</script>
</p>
</body>
</html>

The second file, datetime.js, will contain only JavaScript commandsthe same ones you removed from the HTML file. This file should not include <script> tags, or any HTML tags. The JavaScript file is shown in Listing 2.5.

Listing 2.5. The Date and Time Script (datetime.js)
now = new Date();
localtime = now.toString();
utctime = now.toUTCString();
document.write("<b>Local time:</b> " + localtime + "<BR>");
document.write("<b>UTC time:</b> " + utctime);
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write("<h1>");
document.write(hours + ":" + mins + ":" + secs);
document.write("</h1>");
By the Way
If Internet Explorer displays a warning message in a yellow bar at the top of the browser window instead of executing your script, simply click the bar and select Allow Blocked Content.

As you create larger scripts, you'll find it far less confusing to keep the HTML and JavaScript in separate files. The next hour discusses this and other best practices for JavaScript.

During this hour, you wrote a simple JavaScript program and tested it using a browser. You learned about the tools you need to work with JavaScript, basically, an editor and a browser. You also learned how to modify and test scripts, and what happens when a JavaScript program runs into an error. Finally, you learned how to use scripts in separate JavaScript files.

In the process of writing this script, you have used some of JavaScript's basic features: variables, the document.write statement, and functions for working with dates and times.

Now that you've learned a bit of JavaScript syntax, you're ready to learn more of the details. You'll do that in Hour 3, "Getting Started with JavaScript Programming."

Q1:

Why do I need more than one browser to test scripts? Won't JavaScript behave the same way on both browsers?

A1:

Although JavaScript is standardized, the browsers don't interpret it in exactly the same way. Your script might have minor flaws that have no effect in one browser but cause an error in another. Also, as you move on to more advanced features of JavaScript, you'll need to deal with browsers in different ways, as described in Hour 15, "Unobtrusive Scripting," and you'll need to test each one.

Q2:

When I try to run my script, the browser displays the actual script in the browser window instead of executing it. What did I do wrong?

A2:

This is most likely caused by one of three errors. First, you might be missing the beginning or ending <script> tags. Check them, and verify that the first reads <script LANGUAGE="JavaScript" type="text/javascript">. Second, your file might have been saved with a .txt extension, causing the browser to treat it as a text file. Rename it to .htm or .html to fix the problem. Third, make sure your browser supports JavaScript, and that it is not disabled in the Preferences dialog.

Q3:

Why are the <b> and <br> tags allowed in the statements to print the time? I thought HTML tags weren't allowed within the <script> tags.

A3:

Because this particular tag is inside quotation marks, it's considered a valid part of the script. The script's output, including any HTML tags, is interpreted and displayed by the browser. You can use other HTML tags within quotation marks to add formatting, such as the <h1> tags we added for the large clock display.

Quiz Questions

wax ka badal

Test your knowledge of JavaScript by answering the following questions:

1.

What software do you use to create and edit JavaScript programs?

A browser

A text editor

A pencil and a piece of paper

2.

What are variables used for in JavaScript programs?

Storing numbers, dates, or other values

Varying randomly

Causing high school algebra flashbacks

3.

What should appear at the very end of a JavaScript script embedded in an HTML file?

The <script LANGUAGE="JavaScript"> tag

The </script> tag

The END statement

Quiz Answers

wax ka badal

1.

b. Any text editor can be used to create scripts. You can also use a word processor if you're careful to save the document as a text file with the .html or .htm extension.

2.

a. Variables are used to store numbers, dates, or other values.

3.

b. Your script should end with the </script> tag.

To further your knowledge of JavaScript, perform the following exercises:

Add a millisecond field to the large clock. You can use the getMilliseconds function, which works just like getSeconds but returns milliseconds.

Modify the script to display the time, including milliseconds, twice. Notice whether any time passes between the two time displays when you load the page.

-->