Chapter 10. The window Object

The JavaScript language is based upon a standard called ECMAScript, and you can find ECMAScript used in a variety of applications and technologies. Flash has its own ECMAScript version called ActionScript, which is similar to JavaScript.

ECMAScript is most widely used, however, in web browsers, and chances are pretty good that you purchased this book and DVD to learn how to use JavaScript this way. Your wait is over (kind of).

The web browser is a JavaScript developer's platform, and every platform has what's called an Application Programming Interface, or API. An API is a set of objects and data types that allow a developer to interact with a particular platform. The web browser has two main APIs: the Browser Object Model (BOM) and the Document Object Model (DOM).

The BOM is an API to program certain aspects of the browser. It enables you to determine what web browser a user is currently using, to open and resize windows, and to navigate to a different page or website. Its primary focus is the browser window.

The DOM is another API that allows you to manipulate the HTML page loaded into the browser. You can find, add, and remove elements within the HTML document, change their appearance, and completely relocate them to different parts of the screen. The DOM's focus is the HTML document.

This lesson introduces you to the main object in the BOM: the window object. This object represents the browser window that contains the HTML page, and it allows you to manipulate many aspects of the browser window. Its most important purpose is to serve as JavaScript's global scope.

THE GLOBAL SCOPE

You've seen many references to global scope throughout this book. Every JavaScript implementation has a global scope, and in the browser the global scope is the window object. It is the topmost object, and all other objects related to the browser window or HTML document are considered members of the window object.

Variables and Functions Are Properties and Methods

You have, in fact, used the window object in every lesson so far. The alert() and prompt() functions are actually methods of the window object. In JavaScript the window object is implied, so it's possible to access its properties and methods without explicitly specifying window before a variable or method. For example, as far as the browser is concerned, the following two lines of code are identical:

window.alert("Hello, Browser!");
alert("Hello, Browser!");

This concept can be taken a step further with variables and functions. When you create a variable or function in the global scope, you actually create a property or method of the window object. Look at this code:

var someVariable = "Some value"; // is same as window.someVariable = "Some value";

function showSomeVariable() {
    alert(window.someVariable); // explicitly use window
}

window.showSomeVariable(); // explicitly use window

Here a variable called someVariable is created and given a string value. Next a function called showSomeVariable() is declared; its body contains a call to the alert() method and passes the window.someVariable property to it. The final line of this code explicitly uses the window object to execute the showSomeVariable() method. The result of this code can be seen in Figure 10-1.

Figure 10-1

Figure 10.1. Figure 10-1

All global variables and functions are members of the window object; thus, you can access them by explicitly using the window object. However, it is conventional to omit the explicit use of window unless there is a reason to use it. You'd want to use it, for example, to deal with scope when a local variable within a function has the same name as a global variable. Consider the following code:

var someVariable = "Global value";

function showSomeVariable() {
    var someVariable = "Local value";

    alert(someVariable); // Local value
    alert(window.someVariable); // Global value
}

In this code a global variable called someVariable is initialized with a string value. Next the showSomeVariable() function is declared, and its first statement is the initialization of a variable called someVariable — the same name as the global variable. Inside the function, the someVariable identifier refers to the local variable. In order to access the global variable with the same name, you must prepend it with window; otherwise, JavaScript retrieves the local variable.

The general rule of thumb is to omit window unless you absolutely need to explicitly specify the global object.

The this Variable

In Lesson 8, you learned how to create custom data types by writing a constructor function and using the this variable inside it to create properties. The end of Lesson 8 instructed you to always use the new keyword when calling a constructor function. Now that you know that global functions are actually methods of the window object, you can begin to see what happens when you call a constructor function without the new keyword. First, here is some code that correctly calls a custom data type's constructor:

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

var person = new Person("Jeremy", "McPeak");

This code creates a Person data type and correctly calls the constructor for that data type. A new Person object is created and assigned to the person variable. There is nothing wrong with this code. Compare it to the following code, which omits the new keyword:

var person2 = Person("Jeremy", "McPeak");

Here a statement calls the Person() function without prefixing it with new. JavaScript sees the call as being like any other function call and executes it. Because Person("Jeremy", "McPeak") is the same as window.Person("Jeremy", "McPeak"), the this variable is bound to the window object; therefore, the code within the function creates two global variables, firstName and lastName, and assigns them a value of whatever was passed to the function. Also, since Person() does not return a value, the person2 variable contains a value of undefined. So not only has this code added unnecessary variables to the global scope, but code depending on person2 breaks because person2 is undefined instead of a Person object.

Again, it is very, very important to always use the new keyword when calling a constructor function.

SHOWING AND USING DIALOG BOXES

Dialog boxes have a vital role in just about every application. They provide all sorts of information to the user, such as general information and error messages, and they can allow the user to input data or make a decision. Web browsers are no exception, and the window object gives developers access to three dialog boxes: the alert dialog, the prompt dialog, and the confirm dialog. When the browser displays one of these, JavaScript execution is halted until the box is closed. You've seen two of these dialog boxes used throughout the previous lessons, but let's go over all of them to be thorough.

The Alert Dialog Box

The alert dialog box is used to display a message to the user. The window contains one OK button, which is used to close the dialog. Closing the alert box does not cause any special JavaScript to run; it's simply a box to display information. Figure 10-2 shows an alert box in the Chrome browser.

Figure 10-2

Figure 10.2. Figure 10-2

The code that generates the alert box in this figure is as follows:

alert("Hello, Alert box!");

Use the alert() method to show this type of dialog. Its only parameter is the data to display to the user. If you want to get a user's input with a dialog box, use the prompt() method.

The Prompt Dialog Box

The prompt dialog box's purpose is to prompt the user to input data. Figure 10-3 shows what a prompt dialog box looks like in Chrome.

Figure 10-3

Figure 10.3. Figure 10-3

The prompt box might look different in other browsers, but they all have the same basic components: a message to the user, a textbox, an OK button, and a Cancel button. The following code generates the prompt seen in Figure 10-3:

var name = prompt("Please enter your name.", "Default Text");

The prompt() method accepts two arguments. The first is the message to display to the user. The second is optional and determines the default text entered in the textbox.

Clicking OK causes the prompt method to return the text typed into the textbox to the caller. In the case of this code, the value of the name variable depends on what text is in the textbox when the user clicks OK. If the user clicks Cancel, the prompt() method returns null. Therefore, when relying on the prompt() method to get data from the user, make sure the data returned is not null, like this:

if (name != null) {
    // do something with data
}

The prompt() method is an obtrusive means of getting data from the user. From a user-interface perspective, form elements within a web page are a better means of acquiring text-based user input. Not only can form elements take on the look and feel of your web application, but you can acquire multiple pieces of data without having to display an ugly pop-up window for user input.

There is, however, a dialog box that gets input from the user that is ideal in some situations.

The Confirm Dialog Box

Sometimes you want the user to decide how your program should behave. You see this type of dialog box frequently in some operating systems. For example, a dialog box may ask you if you really do want to delete a file when you press the Delete key with a file selected. It waits for your input and deletes the file if you chose Yes. This is the idea behind the confirm dialog box. Its purpose is to provide the user with a yes-or-no option, and your application can process data according to the user's input.

You can show the confirm dialog box by calling the confirm() method. It accepts an argument containing a message to display to the user, and it returns a Boolean value based on the button the user presses. The following code uses the confirm() method in an if statement:

if (confirm("Is it sunny today?")) {
    alert("Let's go outside");
} else {
    alert("Let's stay inside");
}

Here a confirm dialog box is shown in Figure 10-4 to the user, asking if it's sunny outside. If the user clicks OK, the confirm() method returns true and an alert box displays the text "Let's go outside." If the user clicks Cancel, he or she sees a message that says, "Let's stay inside."

Figure 10-4

Figure 10.4. Figure 10-4

The confirm dialog box allows your application to be considerate of the user by asking the user's permission to execute code that performs an obtrusive action, such as navigating unexpectedly to another web page using the location object.

THE LOCATION OBJECT

The window object has a property called location; it's an object that contains information about the current URL loaded in the browser. The two main uses of the location object are to reload the current page and to navigate to a new page.

Reloading the Page

There are many ways to reload a web page in the browser. It's common to find the <meta/> element used to reload the page after a set amount of time, but JavaScript is typically a better solution, as you can control how the page refreshes itself to fit the needs of your application.

To reload the page you use the reload() method. It accepts an optional Boolean argument that determines if the browser performs a full refresh in the event that the webserver says the document hasn't been modified. If the webserver responds that a web page hasn't been modified since it was last requested by the browser, the browser normally loads the page from its cache. By passing a value of true to the reload() method, you can ensure that the document is always retrieved from the webserver; omitting the parameter lets the browser load the page from the cache. The following code demonstrates the use of the reload() method:

location.reload(true);

Here the reload() method is called on the location object. Remember that window is implied, so this code actually translates to window.location.reload(true). A value of true is passed to this method, so it will always retrieve the page from the webserver.

Navigating to Another Page

Navigating away from the current page to another is probably the most common action for which the location object is used. There are two ways to do this: The first is to use the location object's href property, like this:

location.href = "http://www.google.com";

This code assigns a new URL to the href property, and the browser automatically navigates to the page (Google's search page in this case). You can, however, simplify this code by omitting the href property:

location = "http://www.google.com";

This code performs the same function as the previous example, and it's actually the preferred method of navigating to a different page.

TRY IT

In this lesson you learn about the window object and its global nature. You also learn about the dialog boxes it provides you with, as well as the ability to reload the page and navigate to another page.

Lesson Requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/). Mac OS X users can use TextMate, which comes as part of OS X, or they can download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

  • Internet Explorer 8+

  • Google Chrome

  • Firefox 3.5+

  • Apple Safari 4+

  • Opera 10+

Create a subfolder called Lesson10 in the JS24Hour folder you created in Lesson 1. Store the files you create in this lesson in the Lesson10 folder.

Step-by-Step

Write a simple application that either navigates to a different page or reloads the current page, based on the user's input.

  1. Open your text editor and type the following code:

    if (confirm("Do you want to go to Google?")) {
        location = "http://www.google.com";
    }

    This code shows a confirm dialog box asking the user if he or she wants to go to another web page. If the user clicks OK, the browser will go to Google's website.

  2. Now add an else block to reload the page. It is bolded in the following code:

    if (confirm("Do you want to go to Google?")) {
        location = "http://www.google.com";
    } else {
        location.reload(true);
    }
  3. Save the file as lesson10_sample01.js.

  4. Open another instance of your text editor, type the following HTML, and save it as lesson10_sample01.htm:

    <html>
    <head>
        <title>Lesson 9: The window Object</title>
    </head>
    <body>
        <script type="text/javascript" src="lesson10_sample01.js"></script>
    </body>
    </html>
  5. Open the HTML file in your browser. A dialog box will ask whether or not you want to go to Google. Click OK to go there, or Cancel to reload the current page.

To get the sample code files you can download Lesson 10 from the book's website at www.wrox.com.

Note

Please select Lesson 10 on the DVD to view the video that accompanies this lesson.

Step-by-Step
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.201