Chapter 5: Programming the Browser

Overview

Over the past three chapters, we've examined the core JavaScript language. We've seen how to work with variables and data, perform operations on that data, make decisions in our code, loop repeatedly over the same section of code, and even how to write our own functions. In the preceding chapter we moved on to learn how JavaScript is an object-based language, and we saw how to work with the native JavaScript objects. However, we are not just interested in the language itself—we want to find out how to write script for the web browser. Using this, we can start to create more impressive web pages.

Not only is JavaScript object-based, but the browser is also made up of objects. When JavaScript is running in the browser, we can access the browser's objects in exactly the same way we used JavaScript's native objects in the last chapter. But what kinds of objects does the browser provide for us to use?

The browser makes available to us a remarkable number of objects. For example, there is a window object corresponding to the window of the browser. We have already been using two methods of this object, namely the alert() and prompt() methods. For simplicity we previously called these functions, but they are in fact methods of the browser's window object.

Another object made available by the browser is the page itself, represented by the document object. Again, we have already used methods and properties of this object. Recall from Chapter 1 that we used the document object's bgColor property to change the background color of the page. We have also been using the write() method of the document object to write information to the page.

A variety of other objects exist, representing a lot of the HTML that we write in the page. For example, there is an img object for each <img> tag that we use to insert an image into our document.

The collection of objects that the browser makes available to us for use with JavaScript is generally called the Browser Object Model (BOM).

Note

You will often see this termed the Document Object Model (DOM). However, throughout this book, we'll use the term DOM to refer to the W3C's standard Document Object Model, which is discussed in Chapter 13.

All this added functionality that JavaScript has comes with a downside. The collections of objects that are made available to us are highly dependent on the brand and version of the browser that we are using. Some objects are made available in some browsers and not in others, while other objects have different properties and methods in different browsers. We will see more about the differences between the BOM of IE and NN browsers in Chapter 12.