Chapter 1. Jump-Starting JavaScript

CONTENTS

CONTENTS>>

  •  JavaScript Lives in a Web Page
  •  Putting JavaScript into Your HTML Pages
  •  What You Can Do with JavaScript That You Can't Do with HTML
  •  An Interpreted Language
  •  A Tale of Two Interpreters
  •  Generated JavaScript
  •  Summary

Getting Started With JavaScript is like beginning any other scripting, or programming, language. To learn it, you have to use it. JavaScript is the "engine" that makes things move on a page; by working with dynamic design elements, the more you see what can be done with JavaScript and the more incentive there is to learn to use it. JavaScript allows designers to release those aspects of design creativity that cannot be expressed in static HTML.

You need not look very far to find a use for JavaScript, and so opportunities abound for learning the language rollovers, moving text, prompt windows, and alert boxes are just a few of the actions powered by JavaScript. JavaScript is a ranged language. It ranges from extremely simple built-in functions and statements that can make your page jump to fairly sophisticated coding structures. By beginning with the simple, you can ease your way to its more complex and powerful structures as dictated by design needs. It doesn't require a compiler or a degree in computer science to learn. It lives right among the HTML tags, and most JavaScript programs are relatively small, so you're not spending all your life writing hundreds of lines of code.

Throughout this book, you will see explanations accompanied by examples and applications. However, the applications are really only extensions of some feature or concept in JavaScript. My goal with this book is not merely to enable you to cut and paste snippets of code, but rather to understand JavaScript in a way that you can apply to your own projects. When you master JavaScript, you will be able to imagine a project or design in your mind's eye and then create the JavaScript necessary to make your imagined scene a reality on a web page.

JavaScript captures user events that cause actions to happen on a web page. As a designer who has mastered JavaScript, you will be able to invent new ways that the user interacts with an interactive project.

JavaScript Lives in a Web Page

All the code that you write for JavaScript goes into an HTML page. If you don't know HTML yet, you should run out and get a good book on HTML. Lynda and William Weinman's Creative HTML Design.2 (New Riders, 2001) is a good choice for designers and developers. However, assuming that you are familiar with HTML, you should be familiar with the whole concept of a tag language. HTML stands for Hypertext Markup Language. As a markup language, HTML essentially describes a web page as a static entity. A far more challenging endeavor is to program a web page that is dynamic, engaging, and intriguing. That's where JavaScript comes into play.

The most dynamic elements in HTML, beside the link, are event-related attributes. For example, onClick is one of the event-related attributes of HTML. The HTML attribute launches a script when the user clicks on a portion of the page sensitive to a mouse-click action set up by the HTML. However, because HTML itself has no dynamic components, it relies on scripts written in JavaScript. An event-related attribute in HTML is like having a starter on a car with no engine JavaScript is the engine.

When you have finished an HTML page using solely HTML, the page sits on the screen until you click a link that connects to a separate HTML page, which makes the current page go away.

With JavaScript, you can create pages that make something happen on the page when the person viewing the page takes an action that fires a JavaScript. For example, you might have seen pages that have buttons that change shape or color when the mouse passes over them. That change can be made with a script written in JavaScript and fired by an event-related attribute in HTML: onMouseOver. You are also working on a page that doesn't necessarily have to make server requests. All the interaction is taking place without having to download anything. Depending on the application, this can set the groundwork for instantaneous responsive experiences.

Putting JavaScript into Your HTML Pages

This section contains several scripts written in JavaScript that illustrate some of the things that you can do using JavaScript that cannot be done with HTML alone. All these scripts are simple, but at this point in the book, they are not explained beyond the most general terms. They serve to illustrate where to place JavaScript code and the difference between immediate and deferred working of the script. An immediate script executes as soon as it loads, and a deferred script waits until the user does something to make the script launch.

Most JavaScript is written in a tag container named script. The generic format looks like the following:

<script language="JavaScript"> script goes here </script>

As you will see in the examples throughout this book, the script container is required for most JavaScript, even though a few cases exist in which JavaScript can be applied on the fly. However, you should expect to see the opening and closing <script> tags where you see JavaScript.

CAUTION

Unlike some tags that do not require an ending or closing tag, the <script> absolutely requires a </script> tag. In debugging your script, the first thing to check is to make sure that you put in both tags.

For example, the following is a simple, minimal script of what an HTML page needs for JavaScript to work:

<html> <body> <script language="JavaScript"> document.write("Hello designers and developers."); </script> </body> </html>

The JavaScript container has a single line of JavaScript to be executed as soon as the parser passes over it. The parser is the interpreter that reads the code one line at a time, beginning with the top line. Usually, you will find JavaScript code in the head section of an HTML page. (The area in the <head> </head> container is the head.) All the code in the head section of an HTML page is loaded first; if code is placed in the head, you do not have to worry about the code being only partially loaded when the viewer is ready to fire the JavaScript functions.

What You Can Do with JavaScript That You Can't Do with HTML

The most important feature that JavaScript can add to a web site design is the capability to introduce dynamic interactivity into pages. The concept of dynamic interactivity implies change in response to an action. For example, a design might be one that seeks to engage the viewer in the page. By having page elements that respond to the viewer's action, the designer can have a page that interacts with the viewer rather than just sitting there for the viewer to look at. In one respect, HTML sites are interactively dynamic because the viewer navigates to different places in the site depending on where she clicks on the page. However, the pages themselves are fairly static. With dynamic interactivity on a page, features of the page change as the user moves, clicks, or drags the mouse over the page.

Alerting the Viewer

A useful built-in function in JavaScript is the alert( ) function. This function sends a message to the page. The contents of the message can vary depending on what the user does, or the messages can be static. When the alert box appears with the message, the user clicks to close it. The following example is a very simple one that illustrates how to use a function in a script. Throughout the book, examples using the alert( ) function will help you understand JavaScript, and I think you will find it a good learning tool. Of course, you can use it in more sophisticated ways than what is presented here. When you start writing more complex functions, you will find the alert( ) function valuable in terms of pinpointing problem areas in the function.

Later in the book, you will learn a lot more about functions. However, for now, it is enough to know that JavaScript contains built-in functions that execute a set of instructions to do things like put messages on the screen, prompt users to enter information, and write text to the screen. You may also write your own functions consisting of a set of statements and other functions. Typically, a function's actions are deferred until the user does something, such as click a button, to launch them. However, as you will see in the following script, a function can be fired in the immediate mode.

<html> <head> <title>Simple Alert </title> </head> <body> <script language="JavaScript"> alert("I told you it was simple!"); </script> </body> </html>

The only dynamic interactivity that the user engages is clicking the OK button to remove the message from the screen. However, later in the book, you will see some far more dynamic uses of this handy little function. Figure 1.1 shows what you should see when your page comes up.

Figure 1.1. JavaScript adds interactivity to web pages.

graphics/01fig01.gif

Prompting a Reaction

The second example of dynamic interactivity on a page using JavaScript can be seen using the prompt( ) function. This built-in function can take two arguments. An argument is some value in the function that you can change to different values, whether it is entered in the code itself or whether the user puts it in himself. Thus, a single function can have several different values throughout a single script, and you can use it with several different designs. All you need to change are the arguments in the function; you don't have to rewrite the function even though the design is different. A Cascading Style Sheet (CSS) is added to provide an integrated color system to the page. Chapter 12, "Dynamic HTML," goes into detail about using CSS, but I believe that you should start using CSS in all HTML designs. CSS soon will be replacing tags such as <font> for specifying colors in text, and CSS helps designers better set up color schemes, font sizes and weights, and overall design of a page. Also, you can see how CSS can be integrated into a JavaScript program.

prompt.html
<html> <head> <title>Prompt</title> <style type="text/css" > .prompt { font-family: verdana; font-weight:bold; color: #8b6952; background-color:#d3c75e; font-size:18pt } body { background-color: #db4347 } </style> </title> <body> <center><p><p> <div class=prompt> <script language="JavaScript"> var yourname yourname=prompt("Enter your name:","Name"); document.write("Welcome, " + yourname); </script> </div> </body> </html>

CAUTION

If you use a version other than Version 6 of Netscape Navigator, you will see a different background when using Netscape Navigator and Internet Explorer. Prior to Version 6, the browsers interpreted CSS differently, but current browsers adhere to the standards set by the World Wide Web Consortium (W3C).

The two arguments used in the prompt( ) function are the prompt message that you select (Enter Your Name) and the optional placeholder that appears in the prompt window (Name). When the user opens the page, the script automatically runs. The script is right in the middle of the HTML and is executed as soon as the parser reads and interprets the code. Figure 1.2 shows what the viewer sees when the page opens.

Figure 1.2. The viewer is prompted to enter a name.

graphics/01fig02.gif

After the viewer has entered information, he sees his name on the web page, as shown in Figure 1.3.

Figure 1.3. The information entered by the user now appears on the web page.

graphics/01fig03.gif

Changing Background Colors

The capability to change background colors on the fly allows the designer to get the viewer's attention. First, whenever a background color changes, the viewer is alerted to something different going on, and this change can be used to produce a mood or context that the designer wants to impart. Second, creative designers have used changes in background color to reveal hidden text. White text on a white background is invisible, but as soon as the background turns to black, the white text is revealed and black text is hidden.

This next example shows one of the few places where JavaScript is not required to have a container to first define JavaScript and an example of JavaScript running in the deferred mode. The buttons in the form serve as firing mechanisms for the JavaScript code. No JavaScript is executed until a button is pressed. Unlike the previous two examples, the JavaScript in this script is deferred.

This line:

<input type="button" value="#d0d0a9" onClick="document.bgColor='d0d0a9'">

contains the firing button ("button"), the event handler attribute (onClick), and the built-in JavaScript (document.bgColor=). The CSS code takes up all the room in the head of the page; however, it is important because it not only defines the body text, but also the masked message that appears when the background color changes to reveal text on the page.

colorChange.html
<html> <head> <style type="text/css"> .bText { font-family: verdana; font-weight:bold; font-size:10pt } .surprise { font-weight:bold; color: #cc2801; font-size:24pt } </style> </head> <body bgcolor="#cc2801"> <center> <table border=0 cellpadding=5 cols=1 width="40%" height="40%" >       <tr>            <td align=center valign=center bgcolor="#3c6816">            <p class=bText>Click a button below to change the background color.</p>            <form> <input type="button" value="#d0d0a9" onClick="document.bgColor='d0d0a9'"> <br> <input type="button" value="#794e23" onClick="document.bgColor='#794e23'"> <br> <input type="button" value="#cc2801" onClick="document.bgColor='#cc2801'">            </td>       </tr> </table> <div class=surprise>Surprise!</div> </center> </body> </html>

The preceding listing might seem to be a lot of code for changing background colors, but most of the code relates to the CSS only three lines use the JavaScript. With all the changes that take place on the page, it appears as though several different pages are rapidly sequencing through the browser. However, it's just a single page with a little JavaScript. Figure 1.4 shows what the viewer will see when she changes background colors from the original.

Figure 1.4. By changing background colors, masked messages appear.

graphics/01fig04.gif

A Function to Convert Decimal to Hexadecimal

The heart and soul of JavaScript belongs in functions. In Chapter 6, "Building and Calling Functions," functions are discussed in detail. As noted previously, functions are self-contained clusters of JavaScript. The functions can then be used throughout the page in which they are defined and can be launched using event-related attributes. Furthermore, keep in mind that functions are either built-in, like the alert( ) and prompt( ) functions, or user-defined. A user-defined function is one that the programmer writes and uses in her page. However, the built-in and userdefined functions work and are launched in the same way.

This next script uses a function that converts three sets of decimal numbers into a hexadecimal number. While relatively complex for the first chapter, the purpose of the script is to show you something very practical that you can do with JavaScript. To get an exact match between colors that you develop in graphic programs such as Adobe Photoshop and your web page, you need to change the decimal RGB (red, green, blue) colors into a hexadecimal value. For example, a rich red has the following values:

R=169 G=23 B=35

To use those numbers, they have to be translated into a six-character hexadecimal value that you can see in the following CSS definition:

Body { background-color: a91723;}

You can find lots of decimal-to-hexadecimal converters on the web, but because you want to convert colors, you need the conversion in groups of three for the red, green, and blue values. Taking the three decimal values, your converter should convert the colors into a single six-character hexadecimal value. The following program does just that.

NOTE

If you're new to programming, do not be intimidated by the code in this next script. In the following several chapters, you will be introduced gradually to the kind of code and structures that allow you to build more sophisticated JavaScript programs. This one is simply an example of what you can do with JavaScript and one that you can use to convert decimal values into hexadecimal ones for use in your pages.

decimal2hex.html
<html> <head> <style> body { font-family: verdana; background-color: a91723; color: fcc0b9; font-weight:bold; font-size:10pt } </style> <title>Decimal To Hex Conversion</title> <script language="JavaScript"> function dec2hex( ) { var accum=" "; for (var i=0;i<3;i++) {       var dec=document.convert.elements[i].value;       var toNum=Math.floor(dec);       var toHex=toNum.toString(16);              if (toHex.length==1) {              toHex= "0"+toHex;              }       accum += toHex;       } document.convert.hex.value=accum; } </script> </head> <body > <center><br> Decimal to Hexadecimal Converter </center><br> <form name="convert"> <input type="text" name="dec1" size=3> <input type="text" name="dec2" size=3> <input type="text" name="dec3" size=3> <-Enter decimal numbers here:<br> <input type="text" name="hex" size=6> &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <-View hexadecimal number here:<p> <input type="button" value="Convert to hexadecimal" onClick="dec2hex( )"> </p> </body> </html>

The big line of &nbsp (nonbreaking spaces) is simply for adding spaces a formatting chore. The script uses data entered by the web page viewer in the form windows. The function converts each decimal number using a loop, checking for single-digit results that require a leading zero (0), and then builds a string containing six characters that make up the hexadecimal values. Finally, the function sends the results to the viewer. Figure 1.5 shows you what the viewer sees when she enters values to be converted into a six-digit hexadecimal value.

Figure 1.5. JavaScript can create very practical and useful applications.

graphics/01fig05.gif

Now that you have seen some examples of what JavaScript can do in collaboration with HTML, the next sections provide some more information about how JavaScript works in your browser.

An Interpreted Language

Some languages are interpreted, and some are compiled. JavaScript is an interpreted language. Your browser, most likely Netscape Navigator or Internet Explorer, acts as a translator between JavaScript and the native language that your computer uses. The process involves your browser parsing (interpreting) the JavaScript code and then creating an equivalent machine language and having your computer execute the interpreted code. Compiled languages such as Java and C++ are already interpreted (compiled), so they go right into the computer, ready to talk with your computer.

The process is something like visiting France and communicating in French. If you don't know French, the easiest way to communicate is with an interpreter who speaks both French and English. It takes a little longer because everything that you say has to be translated into French. Alternatively, you could go to classes to learn to speak French before your visit to France. Learning French will take more time and effort, but when you go to France, you will be understood without an interpreter and communication will go much more quickly.

Interpreted and compiled languages in computers work somewhat along the same lines. Generally, interpreted languages are easier to learn and use, but they take more time to run in your computer. Compiled languages take more time to master, debug, and write, but they execute far more quickly. However, most JavaScript applications are fairly short. The interpreter doesn't have much to interpret good day (bonjour) and so the difference between a complied and interpreted language is often negligible. This is especially true today with the high speeds of modern computers.

A Tale of Two Interpreters

A bit more serious problem exists between the two main interpreters, Netscape Navigator and Internet Explorer. Each has a slightly different way of translating JavaScript. Fortunately, only a few elements are translated differently, but, unfortunately, the differences can create major problems. The European Computer Manufacturer's Association (ECMA) sets standards for JavaScript, and both Netscape and Microsoft generally adhere to these standards. However, for some reason, each has decided to have a slightly different way of interpreting JavaScript; when those differences are encountered, you need to know how to deal with them. In the meantime, be aware that JavaScript's interpretation of a few commands and statements has slightly different structures for the two competing interpreters.

NOTE

To make matters more interesting, both of the major browsers keep improving on their products. At this writing, Netscape Navigator (NN) is part of Version 6 of Netscape Communicator, and Internet Explorer (IE) is in Version 5.5. However, the numbers don't tell us much because NN skipped Version 5 altogether and went from Version 4.7 to Version 6. What is important is that the browsers are interpreters and that the interpreters determine what version of JavaScript each can read. Even though JavaScript 1.3 and 1.5 language elements are available, they're still in testing. Realistically, JavaScript's big developmental change came with JavaScript 1.2. While this book covers the new features added with JavaScript 1.3 and 1.5, most JavaScript in its newest configuration was present when JavaScript 1.2 appeared. The official revision version of JavaScript is ECMA-262, and JavaScript 1.2, 1.3, and 1.5 adhere to ECMA-262 with the exceptions that the browser manufacturers add. When JavaScript 2.0 is complete, you won't have to learn JavaScript all over again. The goal is to have backward compatibility with earlier versions of JavaScript. So, learning JavaScript, where most of the revisions were put into JavaScript 1.2 , is a safe starting place for now and for later revisions.

In the meantime, don't be overly concerned about all these different versions of JavaScript. Just be aware of them. If you use Version 4 and above on either of the major browsers, your JavaScript can be read just fine except where little differences of interpretation exist. You will be alerted to those places where the two major browsers part company and how to deal with the differences.

Generated JavaScript

Many designers have their first developmental encounter with JavaScript when they create web pages with tools such as Macromedia Dreamweaver, Adobe GoLive, or Microsoft FrontPage. Not only will these tools generate JavaScript for you, but they will do it for either or both of the major browsers.

In looking at the code, however, you have no idea of what's going on in the code unless you understand JavaScript. Sometimes the generated code will tap into code in one of its libraries that you cannot see. It will connect to an external .js file containing a good deal of code that you won't see, but can be fairly complex. If you want to change it or even tweak it a little with added or altered code, you're lost. So, the first goal in learning JavaScript is to be able to fine-tune JavaScript generated in your web site development tools.

Second, you might want to learn JavaScript to lighten the amount of code that some site development tools generate. Jakob Nielsen, author of Designing Web Usability (New Riders, 1999), points out that site-development tools sometimes cause "code bloat." That is, the generic code developed in the site tools sometimes generates more code than is absolutely necessary, and you can cut it down. The reason you want to avoid code bloat is that it creates a larger file than you need, so it loads slower. For example, take a look at the following script:

<html> <head> <title>Swap Simple</title> <script language="JavaScript"> var sample2= new Image( ) sample2.src="sample2.gif" var sample1=new Image( ) sample1.src="sample1.gif" function switch2( ) {             document.sample.src=sample2.src } function switch1( ) {             document.sample.src=sample1.src }  </script></head> <body> <a href="#" onMouseOver="switch2( )" onMouseOut="switch1( )"> <img name="sample" src="sample1.gif" border=0></a> </body> </html>

This code is quite simple (if you know JavaScript) and accomplishes the same rollover effect as code generated in one of the web site development tools. However, it is a good deal clearer to understand because all of the elements are laid out and available, whereas code generated by site development tools can often mask many of the key elements that make your code do what you want.

Summary

This chapter's goal has been to provide a glimpse of JavaScript and a little understanding of what it can do. JavaScript ranges from very simple but useful applications to very complex scripts that handle complex tasks. Don't expect to learn the language all at once, but do begin to think about designs that can be aided by the inclusion of JavaScript in your web pages. Include interactive elements in your pages using JavaScript so that the viewer is engaged in the page rather than a passive audience. Like all languages, the more you use it, the easier it becomes to apply in your web pages. So, start using the language right away.

JavaScript is interpreted by your browser, and while different browsers can require different scripting strategies, most JavaScript follows the ECMA-262 standard. However, be aware that some nagging differences exist. In later chapters, you will be prepared with strategies for dealing with these differences.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

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