Chapter 13. Exploring JavaScript

JavaScript brings a dynamic functionality to your websites. Every time you see something pop up when you mouse over an item in the browser, or see new text, colors, or images appear on the page in front of your eyes, or grab an object on the page and drag it to a new location—all those things are done through JavaScript. It offers effects that are not otherwise possible, because it runs inside the browser and has direct access to all the elements in a web document.

JavaScript first appeared in the Netscape Navigator browser in 1995, coinciding with the addition of support for Java technology in the browser. Because of the initial incorrect impression that JavaScript was a spin-off of Java, there has been some long-term confusion over their relationship. However, the naming was just a marketing ploy to help the new scripting language benefit from the popularity of the Java programming language.

JavaScript gained new power when the HTML elements of the web page got a more formal, structured definition in what is called the Document Object Model, or DOM. The DOM makes it relatively easy to add a new paragraph or focus on a piece of text and change it.

Because both JavaScript and PHP support much of the structured programming syntax used by the C programming language, they look very similar to each other. They are both fairly high-level languages, too; for instance, they are weakly typed, so it’s easy to change a variable to a new type just by using it in a new context.

Now that you have learned PHP, you should find JavaScript even easier. And you’ll be glad you did, because it’s at the heart of the Web 2.0 Ajax technology that provides the fluid web frontends that (along with HTML5 features) savvy web users expect these days.

JavaScript and HTML Text

JavaScript is a client-side scripting language that runs entirely inside the web browser. To call it up, you place it between  opening <script> and closing </script> HTML tags. A typical HTML 4.01 “Hello World” document using JavaScript might look like Example 13-1.

Example 13-1. “Hello World” displayed using JavaScript
<html>
  <head><title>Hello World</title></head>
  <body>
    <script type="text/javascript">
      document.write("Hello World")
    </script>
    <noscript>
      Your browser doesn't support or has disabled JavaScript
    </noscript>
  </body>
</html>
Note

You may have seen web pages that use the HTML tag <script language="javascript">, but that usage has now been deprecated. This example uses the more recent and preferred <script type="text/javascript">, or you can just use <script> on its own if you like.

Within the <script> tags is a single line of JavaScript code that uses its equivalent of the PHP echo or print commands, document.write. As you’d expect, it simply outputs the supplied string to the current document, where it is displayed.

You may also have noticed that, unlike with PHP, there is no trailing semicolon (;). This is because a newline serves the same purpose as a semicolon in JavaScript. However, if you wish to have more than one statement on a single line, you do need to place a semicolon after each command except the last one. Of course, if you wish, you can add a semicolon to the end of every statement, and your JavaScript will work fine.

The other thing to note in this example  is the <noscript> and </noscript> pair of tags. These are used when you wish to offer alternative HTML to users whose browser does not support JavaScript or who have it disabled. Using these tags is up to you, as they are not required, but you really ought to use them because it’s usually not that difficult to provide static HTML alternatives to the operations you provide using JavaScript. However, the remaining examples in this book will omit <noscript> tags, because we’re focusing on what you can do with JavaScript, not what you can do without it.

When Example 13-1 is loaded, a web browser with JavaScript enabled will output the following (see Figure 13-1):

Hello World
JavaScript, enabled and working
Figure 13-1. JavaScript, enabled and working

A browser with JavaScript disabled will display this message (see Figure 13-2):

Your browser doesn't support or has disabled JavaScript.
JavaScript has been disabled
Figure 13-2. JavaScript has been disabled

Older and Nonstandard Browsers

If you need to support browsers that do not offer scripting, you will need to use the HTML comment tags (<!-- and -->) to prevent them from encountering script code that they should not see. Example 13-2 shows how you add them to your script code.

Example 13-2. The “Hello World” example modified for non-JavaScript browsers
<html>
  <head><title>Hello World</title></head>
  <body>
    <script type="text/javascript"><!--
      document.write("Hello World")
    // --></script>
  </body>
</html>

Here an opening HTML comment tag (<!--) has been added directly after the opening <script> statement and a closing comment tag (// -->) directly before the script is closed with </script>.

The double forward slash (//) is used by JavaScript to indicate that the rest of the line is a comment. It is there so that browsers that do support JavaScript will ignore the following -->, but non-JavaScript browsers will ignore the preceding //, and act on the --> by closing the HTML comment.

Although the solution is a little convoluted, all you really need to remember is to use the two following lines to enclose your JavaScript when you wish to support very old or nonstandard browsers:

<script type="text/javascript"><!—
  (Your JavaScript goes here...)
// --></script>

However, the use of these comments is unnecessary for any browser released over the past several years.

Debugging JavaScript Errors

When you’re learning JavaScript, it’s  important to be able to track typing or other coding errors. Unlike PHP, which displays error messages in the browser, JavaScript handles error messages in a way that changes according to the browser used. Table 13-1 lists how to access JavaScript error messages in each of the five most commonly used browsers.

Table 13-1. Accessing JavaScript error messages in different browsers
Browser How to access JavaScript error messages
Apple Safari Safari does not have an Error Console enabled by default, but you can turn it on by selecting Safari→Preferences→Advanced→“Show Develop menu in menu bar.” However, you may prefer to use the Firebug Lite JavaScript module, which many people find easier to use.
Google Chrome Click the menu icon that looks like a page with a corner turned; then select Developer→JavaScript Console. You can also use the shortcut Ctrl-Shift-J on a PC, or Command-Shift-J on a Mac.
Microsoft Internet Explorer Select Tools→Internet Options→Advanced; then uncheck the Disable Script Debugging box and check the “Display a Notification about Every Script Error” box.
Mozilla Firefox Select Tools→Error Console or use the shortcut Ctrl-Shift-J on a PC, or Command-Shift-J on a Mac.
Opera Select Tools→Advanced→Error Console.
Note

OS X users: Although I have shown you how to create an Error Console for JavaScript, you may prefer to use Google Chrome (for Intel OS X 10.5 or higher).

To try out whichever Error Console you are using, let’s create a script with a minor error. Example 13-3 is much the same as Example 13-1, but the final double quotation mark has been left off the end of the string "Hello World"—a common syntax error.

Example 13-3. A JavaScript “Hello World” script with an error
<html>
  <head><title>Hello World</title></head>
  <body>
    <script type="text/javascript">
      document.write("Hello World)
    </script>
  </body>
</html>

Type the example and save it as test.html; then call it up in your browser. It should succeed only in displaying the title, not anything in the main browser window. Now call up the Error Console in your browser, and you should see a message such as the one in Example 13-4. To the right there will be a link to the source, which, when clicked, shows the error line highlighted (but does not indicate the position at which the error was encountered).

Example 13-4. A Mozilla Firefox Error Console message
SyntaxError: unterminated string literal

In Microsoft Internet Explorer, the error message will look like Example 13-5, and there’s no helpful arrow, but you are given the line and position.

Example 13-5. A Microsoft Internet Explorer Error Console message
unterminated string constant

Google Chrome and Opera will give the message in Example 13-6. Again, you’ll be given the line error number but not the exact location.

Example 13-6. A Google Chrome/Opera Error Console message
Uncaught SyntaxError: Unexpected token ILLEGAL

And Apple Safari provides the message in Example 13-7, with a link to the source on the right stating the line number of the error. You can click the link to highlight the line, but it will not show where on the line the error occurred.

Example 13-7. An Opera Error Console message
SyntaxError: Unexpected EOF

If you find this support a little underwhelming, the Firebug plug-in for Firefox (and now Chrome too) at http://getfirebug.com is very popular among JavaScript developers and is definitely worth a look.

Note

If you will be typing the following code snippets to try them out, don’t forget to surround them with <script> and </script> tags.

Variables

No particular character identifies a variable in JavaScript as the dollar sign does in PHP. Instead, variables use the following naming rules:

And yes, you’re right that is a $ there in that list. It is allowed by JavaScript and may be the first character of a variable or function name. Although I don’t recommend keeping the $ symbols, it means that you can port a lot of PHP code more quickly to JavaScript that way.

Operators

Operators in JavaScript, as in PHP, can involve mathematics, changes to strings, and comparison and logical operations (and, or, etc.). JavaScript mathematical operators look a lot like plain arithmetic; for instance, the following statement outputs 15:

document.write(13 + 2)

The following sections teach you about the various operators.

Arithmetic Operators

Arithmetic operators are used to perform mathematics. You can use  them for the main four operations (addition, subtraction, multiplication, and division) as well as to find the modulus (the remainder after a division) and to increment or decrement a value (see Table 13-2).

Table 13-2. Arithmetic operators
Operator Description Example
+ Addition j + 12
- Subtraction j - 22
* Multiplication j * 7
/ Division j / 3.13
% Modulus (division remainder) j % 6
++ Increment ++j
-- Decrement --j

Comparison Operators

Comparison operators are generally used inside a construct such as an if statement, where you need to compare two items. For example, you may wish to know whether a variable you have been incrementing has reached a specific value, or whether another variable is less than a set value, and so on (see Table 13-4).

Table 13-4. Comparison operators
Operator Description Example
== Is equal to j == 42
!= Is not equal to j != 17
> Is greater than j > 0
< Is less than j < 100
>= Is greater than or equal to j >= 23
<= Is less than or equal to j <= 13
=== Is equal to (and of the same type) j === 56
!== Is not equal to (and of the same type) j !== '1'

Variable Typing

Like PHP, JavaScript is a very loosely typed language; the type of a variable is determined only when a value is assigned and can change as the variable appears in different contexts. Usually, you don’t have to worry about the type; JavaScript figures out what you want and just does it.

Take a look at Example 13-8, in which:

  1. The variable n is assigned the string value 838102050, the next line prints out its value, and the typeof operator is used to look up the type.

  2. n is given the value returned when the numbers 12345 and 67890 are multiplied together. This value is also 838102050, but it is a number, not a string. The type of variable is then looked up and displayed.

  3. Some text is appended to the number n and the result is displayed.

Example 13-8. Setting a variable’s type by assignment
<script>
  n = '838102050'        // Set 'n' to a string
  document.write('n = ' + n + ', and is a ' + typeof n + '<br>')

  n = 12345 * 67890;     // Set 'n' to a number
  document.write('n = ' + n + ', and is a ' + typeof n + '<br>')

  n += ' plus some text' // Change 'n' from a number to a string
  document.write('n = ' + n + ', and is a ' + typeof n + '<br>')
</script>

The output from this script looks like this:

n = 838102050, and is a string
n = 838102050, and is a number
n = 838102050 plus some text, and is a string

If there is ever any doubt about the type of a variable, or you need to ensure that a variable has a particular type, you can force it to that type by using statements such as the following (which respectively turn a string into a number and a number into a string):

n = "123"
n *= 1    // Convert 'n' into a number

n = 123
n += ""   // Convert 'n' into a string

Or, of course, you can always look up a variable’s type by using the typeof operator.

Functions

As with PHP, JavaScript functions are used to separate out sections of code that perform a particular task. To create a function, declare it in the manner shown in Example 13-9.

Example 13-9. A simple function declaration
<script>
  function product(a, b)
  {
    return a*b
  }
</script>

This function takes the two parameters passed, multiplies them together, and returns the product.

Local Variables

Parameters passed to a function automatically  have local scope; that is, they can be referenced only from within that function. However, there is one exception. Arrays are passed to a function by reference, so if you modify any elements in an array parameter, the elements of the original array will be modified.

To define a local variable that has scope only within the current function, and has not been passed as a parameter, use the var keyword. Example 13-10 shows a function that creates one variable with global scope and two with local scope.

Example 13-10. A function creating variables with global and local scope
<script>
  function test()
  {
        a = 123               // Global scope
    var b = 456               // Local scope
    if (a == 123) var c = 789 // Local scope
  }
</script>

To test whether scope setting has worked in PHP, we can use the isset function. But in JavaScript there isn’t one, so Example 13-11 makes use of the typeof operator, which returns the string undefined when a variable is not defined.

Example 13-11. Checking the scope of the variables defined in function test
<script>
  test()

  if (typeof a != 'undefined') document.write('a = "' + a + '"<br>')
  if (typeof b != 'undefined') document.write('b = "' + b + '"<br>')
  if (typeof c != 'undefined') document.write('c = "' + c + '"<br>')

  function test()
  {
    a     = 123
    var b = 456

    if (a == 123) var c = 789
  }
</script>

The output from this script is the following single line:

a = "123"

This shows that only the variable a was given global scope, which is exactly what we would expect, since the variables b and c were given local scope by being prefaced with the var keyword.

If your browser issues a warning about b being undefined, the warning is correct but can be ignored.

The Document Object Model

The designers of JavaScript were very smart. Rather than just creating yet another scripting language (which would have still been a pretty good improvement at the time), they had the vision to build it around the Document Object Model, or DOM. This breaks down the parts of an HTML document into discrete objects, each with its own properties and methods and each subject to JavaScript’s control.

JavaScript separates  objects, properties, and methods by using a period (one good reason why + is the string concatenation operator in JavaScript, rather than the period). For example, let’s consider a business card as an object we’ll call card. This object contains properties such as a name, address, phone number, and so on. In the syntax of JavaScript, these properties would look like this:

card.name
card.phone
card.address

Its methods are functions that retrieve, change, and otherwise act on the properties. For instance, to invoke a method that displays the properties of object card, you might use syntax such as this:

card.display()

Have a look at some of the earlier examples in this chapter and look at where the statement document.write is used. Now that you understand how JavaScript is based around objects, you will see that write is actually a method of the document object.

Within JavaScript, there is a hierarchy of parent and child objects, which is what is known as the Document Object Model (see Figure 13-3).

Example of DOM object hierarchy
Figure 13-3. Example of DOM object hierarchy

The figure uses HTML tags that you are already familiar with to illustrate the parent/child relationship between the various objects in a document. For example, a URL within a link is part of the body of an HTML document. In JavaScript, it is referenced like this:

url = document.links.linkname.href

Notice how this follows the central column down. The first part, document, refers to the <html> and <body> tags; links.linkname to the <a> tag; and href to the href attribute.

Let’s turn this into some HTML and a script to read a link’s properties. Type Example 13-12 and save it as linktest.html; then call it up in your browser.

Note

If you are using Microsoft Internet Explorer as your main development browser, please just read through this section, then read the section entitled “But It’s Not That Simple”, and finally come back here and try the example with the getElementById modification discussed there. Without it, this example will not work for you.

Note the short form of the <script> tags where I have omitted the parameter type="text/JavaScript" to save you some typing. If you wish, just for the purposes of testing this (and other examples), you could also omit everything outside of the <script> and </script> tags. The output from this example is as follows:

Click me
The URL is http://mysite.com

The second line of output comes from the document.write method. Notice how the code follows the document tree down from document to links to mylink (the id given to the link) to href (the URL destination value).

There is also a short form that works equally well, which starts with the value in the id attribute: mylink.href. So you can replace this:

url = document.links.mylink.href

with the following:

url = mylink.href

But It’s Not That Simple

If you tried Example 13-12 in Safari, Firefox, Opera, or Chrome, it will have worked just great. But in Internet Explorer it will fail, because Microsoft’s implementation of JavaScript, called JScript, has many subtle differences from the recognized standards. Welcome to the world of advanced web development!

So what can we do about this? Well, in this case, instead of using the links child object of the parent document object, which Internet Explorer balks at, you have to replace it with a method to fetch the element by its id. Therefore, the following line:

url = document.links.mylink.href

can be replaced with this one:

url = document.getElementById('mylink').href

And now the script will work in all major browsers. Incidentally, when you don’t have to look up the element by id, the short form that follows will still work in Internet Explorer, as well as the other browsers:

url = mylink.href

Using the DOM

The links object is actually an array of URLs, so the mylink URL in Example 13-12 can also be safely referred to on all browsers in the following way (because it’s the first, and only, link):

url = document.links[0].href

If you want to know how many links there are in an entire document, you can query the length property of the links object like this:

numlinks = document.links.length

You can therefore extract and display all links in a document like this:

for (j=0 ; j < document.links.length ; ++j)
  document.write(document.links[j].href + '<br>')

The length of something is a property of every array, and many objects as well. For example, the number of items in your browser’s web history can be queried like this:

document.write(history.length)

However, to stop websites from snooping on your browsing history, the history object stores only the number of sites in the array: you cannot read from or write to these values. But you can replace the current page with one from the history, if you know what position it has within the history. This can be very useful in cases in which you know that certain pages in the history came from your site, or you simply wish to send the browser back one or more pages, which you do with the go method of the history object. For example, to send the browser back three pages, issue the following command:

history.go(-3)

You can also use the following methods to move back or forward a page at a time:

history.back()
history.forward()

In a similar manner, you can replace the currently loaded URL with one of your choosing, like this:

document.location.href = 'http://google.com'

Of course, there’s a whole lot more to the DOM than reading and modifying links. As you progress through the following chapters on JavaScript, you’ll become quite familiar with the DOM and how to access it.

About document.write

When teaching programming it’s necessary to have a quick and easy way to display the results of expressions. In PHP (for example) there are the echo and print statements, which simply send text to the browser, so that’s easy. In JavaScript, though, there are the following alternatives.

Writing into Elements

It is possible to write directly into the text of an HTML element, which is a fairly elegant solution (and the best one for production websites), except that for this book every example would require such an element to be created, and some lines of JavaScript code to access it. This gets in the way of teaching the core of an example and would make the code look overly cumbersome and confusing.

Using document.write

The document.write function writes a value or expression at the current browser location, and is therefore the perfect choice for quickly displaying results, because it keeps all the examples short and sweet, by placing the output right there in the browser next to the web content and code.

You may, however, have have heard that this function is regarded as unsafe by some developers, because when you call it after a web page is fully loaded, it will overwrite the current document. While this is correct, it doesn’t apply to any of the examples in this book, because they all use document.write the way it was originally intended; as part of the page creation process, calling it only before the page has completed loading and displaying.

However, although I use document.write in this way for simple examples, I never use it in production code (except in the very rarest of circumstances, where it actually is necessary). Instead I almost always use the preceding option of writing directly into a specially prepared element, as per the more complex examples in Chapter 17 onward (which access the innerHTML property of elements for program output).

So please remember that where you see document.write being called in this book, it is there only to simplify an example, and I recommend that you also only use the function in the same way—for obtaining quick test results.

With that caveat explained, in the following chapter we’ll continue our exploration of JavaScript by looking at how to control program flow and write expressions.