Windows and Frames

30 248 0
Windows and Frames

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 13. Windows and Frames Chapter 12 described the Window object and the central role it plays in client-side JavaScript. We've seen that the Window object serves as the global object for client-side JavaScript programs, and, as illustrated in Figure 12-1, it is also the root of the client-side object hierarchy. Besides Every web browser window and every frame within every window is represented by a Window object. The Window object defines quite a few properties and methods that are important in client-side JavaScript programming. This chapter explores those properties and methods and demonstrates some important techniques for programming with windows and frames. Note that because the Window object is so central to client-side program is quite long. Don't feel you have to master all this material at once -- you may find it easier to study this chapter in several shorter chunks! verview We beg and me more detail. As usual, the client-side reference section contains complete coverage of Window object properties and methods. The most important properties of the Window object are the following: A boolean value that is only if the window has been closed. defaultStatus, status ext that appears in the status line of the browser. docum that represents the HTML document e Document object is covered in detail in Chapter 14 these special roles, the Window object is an important object in its own right. ming, this chapter 13.1 Window O in this chapter with an overview of some of the most commonly used properties thods of the Window object. Later sections of the chapter explain this material in closed true The t ent A reference to the Document object displayed in the window. Th . frames[] that represent the frames (if any) within the window.An array of Window objects history resents the user's browsing history for location represents the URL of the document t property causes the browser to load a new name The name of the window. Can be used with the target attribute of the HTML <a> tag, for example. parent If the current window is a frame, a reference to the frame of the window that contains it. self A self-referential property; a reference to the current Window object. A synonym for window. top If the current window is a frame, a reference to the Window object of the top- level window that contains the frame. Note that top is different from parent for frames nested within other frames. window A reference to the History object that rep the window. A reference to the Location object that displayed in he window. Setting this document. opener A reference to the Window object that opened this one, or null if this window was opened by the user. A self-referential property; a reference to the current Window object. A synonym for self. The Window object also supports a number of important methods: alert( ) , confirm( ), prompt( ) Display simple dialog boxes to the user and, for confirm( ) and prompt( ), get the user's response. close( ) Close the window. focus( ) , blur( ) Request or relinquish keyboard focus for the window. The focus( ) method also ensures that the window is visible by bringing it to the front of the stacking order. moveBy( ) , moveTo( ) Move the window. open( ) Open a new top-level window to display a specified URL with a specified set of features. print( ) Print the window or frame -- same as if the user had selected the Print button from the window's toolbar (Netscape 4 and later and IE 5 and later only). resizeBy( ) , resizeTo( ) Resize the window. scrollBy( ) , scrollTo( ) Scroll the document displayed within the window. y between invocations. ut( ) milliseconds. .2 Simple Dialog Boxes Three commonly used Window methods are alert( ) , confirm( ), and prompt( ). ed setInterval( ) , clearInterval( ) Schedule or cancel a function to be repeatedly invoked with a specified dela setTimeout( ) , clearTimeo Schedule or cancel a function to be invoked once after a specified number of As you can see from these lists, the Window object provides quite a bit of functionality. The remainder of this chapter explores much of that functionality in more detail. 13 These methods pop up simple dialog boxes. alert( ) displays a message to the user, confirm( ) asks the user to click an Ok or Cancel button to confirm or cancel an boxes producoperation, and prompt( ) asks the user to enter a string. Sample dialog by these three methods are shown in Figure 13-1. Figure 13-1. alert( ), confirm( ), and prompt( ) dialog boxes Note that the text displayed by these dialog boxes is plain text, not HTM format these dialog boxes only with spaces, newlines, and vari L-formatted text. You can ous punctuation characters. Adjusting the layout generally requires trial and error. Bear in mind, though, that the dialog boxes look different on different platforms and in different browsers, so you can't always count on your formatting to look right on all possible browsers. Some browsers (such as Netscape 3 and 4) display the word "JavaScript" in the titlebar or upper-left corner of all dialog boxes produced by alert( ), confirm( ), and prompt( ) . Although designers find this annoying, it should be considered a feature instead of a bug: it is there to make the origin of the dialog box clear to users and to prevent you from writing Trojan-horse code that spoofs system dialog boxes and tricks users into entering their passwords or doing other things that they shouldn't do. The confirm( ) and prompt( ) methods block -- that is, those methods do not return until the user dismisses the dialog boxes they display. This means that when you pop up one of these boxes, your code stops running and the currently loading document, if any, stops loading until the user responds with the requested input. There is no alternative to blocking for these methods -- their return value is the user's input, so they must wait for the user before they can return. In most browsers, the alert( ) method also blocks and waits for the user to dismiss the dialog box. In some browsers, however (notably Netscape 3 and 4 on Unix platforms), alert( ) does not block. In practice, this minor incompatibility rarely causes problems. Example 13-1 shows some typical uses of these methods. Example 13-1. Using the alert( ), confirm( ), and prompt( ) methods n will take some time and that the user should // be patient. It would be suitable for use in the onsubmit event s. arn_on_submit( ) { alert("\n_________________________________________________ _\n\n" + " Your query is being submitted .\n" + "_________________________________________________ _\n\n" + "Please be aware that complex queries such as yours\n" + " can require a minute or more of search time.\n\n" + " Please be patient."); } // Here is a use of the confirm( ) method to ask if the user really // wants to visit a web page that takes a long time to download. Note that // the return value of the method indicates the user response. Based // on this response, we reroute the browser to an appropriate page. var msg = "\nYou are about to experience the most\n\n" + " -=| AWESOME |=-\n\n" + "web page you have ever visited!!!!!!\n\n" + "This page takes an average of 15 minutes to\n" + "download over a 56K modem connection.\n\n" + "Are you ready for a *good* time, Dude????"; if (confirm(msg)) location.replace("awesome_page.html"); else location.replace("lame_page.html"); rs typically display a status line at the bottom of every window (except for messages to the user. n the user moves the mouse over a imple context help message that // Here's a function that uses the alert( ) method to tell the user // that form submissio handler // of an HTML form. // Note that all formatting is done with spaces, newlines, and underscore function w // Here's some very simple code that uses the prompt( ) method to get // a user's name and then uses that name in dynamically generated HTML. n = prompt("What is your name?", ""); document.write("<hr><h1>Welcome to my home page, " + n + "</h1><hr>"); 13.3 The Status Line Web browse those explicitly created without one), where the browser can display When the user moves the mouse over a hypertext link, for example, the browser usually displays the URL to which the link points. And whe wser control button, the browser may display a sbro explains the purpose of the button. You can also make use of this status line in your own eb browsers usually display the URL of a hypertext link when the user passes ehave ed f ote that the event handler *must* return true for this to work. - <map name="map1"> n Center'; return true;"> oords="0,20,50,40" href="order.html" <area coords="0,40,50,60" href="help.html" onmouseover="status='Get help fast!'; return true;"> r true handler displays in the status line with its own URL. Don't worry if you do not fully understand the event handler in this example. We'll explain events in Chapter 19 programs. Its contents are controlled by two properties of the Window object: status and defaultStatus. Although w the mouse pointer over the link, you may have encountered some links that don't b this way -- links that display some text other than the link's URL. This effect is achiev with the status property of the Window object and the onmouseover event handler o hypertext links: <!-- Here's how you set the status line in a hyperlink. -- N -> Lost? Dazed and confused? Visit the <a href="sitemap.html" onmouseover="status='Go to Site Map'; return ue;">tr Site Map </a> <!-- You can do the same thing for client-side image maps --> <img src="images/imgmap1.gif" usemap="#map1"> <area coords="0,0,50,20" href="info.html" useover="status='Visit our Informatio onmo <area c onmouseover="status='Place an order'; return true;"> </map> The onmouseover event handler in this example must return true. This tells the browse that it should not perform its own default action for the event -- that is, it should not display the URL of the link in the status line. If you forget to return , the browser overwrites whatever message the . L w status property -- your custom message is displayed while the mouse is over the hyperlink and is erased when the mouse moves off the link. The status property is intended for exactly the sort of transient message we saw in the previous example. Sometimes, though, you want to display a message that is not so transient in the status line -- for example, you might display a welcome message to users visiting your web page or a simple line of help text for novice visitors. To do this, you set the defaultStatus property of the Window object; this property specifies the default text displayed in the status line. That text is temporarily replaced with URLs, context help When the user moves the mouse pointer over a hyperlink, the browser displays the UR for the link, then erases the URL when the mouse moves off the hyperlink. The same is true when you use an onmouseover event handler to set the Windo messages, or other transient text when the mouse pointer is over hyperlinks or br control buttons, but once the mouse moves off those areas, the default text is restored. You might use the defaultStatus property like this to provide a friendly and helpful message to real beginners: <script> owser defaultStatus = "Welcome! Click on underlined blue text to navigate."; 13.4 Timeouts and Intervals The setTimeout( ) method of the Window object schedules a piece of JavaScript code to be run at some specified time in the future. The clearTimeout( ) method can be used to cancel the execution of that code. setTimeout( ) is commonly used to perform animations or other kinds of repetitive actions. If a function runs and then uses The setTimeout( ) method is commonly used in conjunction with the status or defaultStatus properties to animate some kind of message in the status bar of the browser. In general, animations involving the status bar are gaudy, and you should shun n </script> setTimeout( ) to schedule itself to be called again, we get a process that repeats without any user intervention. JavaScript 1.2 has added the setInterval( ) and clearInterval( ) methods, which are like setTimeout( ) and clearTimeout( ), except that they automatically reschedule the code to run repeatedly; there is no need for the code to reschedule itself. them! There are, however, a few status-bar animation techniques that can be useful and i good taste. Example 13-2 shows such a tasteful status-bar animation. It displays the current time in the status bar and updates that time once a minute. Because the update occurs only once a minute, this animation does not produce a constant flickering distraction at the bottom of the browser window, like so many others do. Note the use of the onload event handler of the <body> tag to perform the first call to the display_time_in_status_line( ) method. This event handler is invoked once when the HTML document is fully loaded into the browser. After this first call, the method uses to schedule itself to be called every 60 seconds so that it can update d time. Examp us line <html> <head> ion displays the time in the status line // Invoke it once to activate the clock; it will call itself from then on functi { setTimeout( ) the displaye le 13-2. A digital clock in the stat <script> // This funct on display_time_in_status_line( ) va var h = d.getHours( ); // Extract hours: 0 to 23 var m = d.getMinutes( ); // Extract minutes: 0 to 59 va if (h > 12) h -= 12; // Convert 24-hour format to 12-hour if (h == 0) h = 12; // Convert 0 o'clock to midnight if minute va defaultStatus = t; // Display it in the status // Arrange to do it all again in one minute setTimeout("display_time_in_status_line( )", 60000); // 60000 ms is one } </script> bother starting the clock till everything is loaded. The anyway <body <!-- The HTML document contents go here --> </body> In JavaScript 1.2, Example 13-2 r d = new Date( ); // Get the current time r ampm = (h >= 12)?"PM":"AM"; // Is it a.m. or p.m.? (m < 10) m = "0" + m; // Convert 0 minutes to 00 s, etc. r t = h + ':' + m + ' ' + ampm; // Put it all together line minute </head> <!-- Don't -- status line will be busy with other messages during loading, . --> onload="display_time_in_status_line( );"> </html> could be written using setInterval( ) instead of the event handler. Instead, after defining display_time_in_status_line( ), our script would call setInterval( ) to schedule an invocation of the function that automatically repeats once every 60,000 milliseconds. 13.5 Error Handling The onerror property of a Window object is special. If you assign a function to this property, the function will be invoked whenever a JavaScript error occurs in that window: the function you assign becomes an error handler for the window. Three arguments are passed to an error handler. The first is a message describing the error that occurred. This may be something like "missing operator in expression", "self is read-only", or "myname is not defined". The second argument is a string that contains the URL of the document containing the JavaScript code that caused the error. The third argument is the line number within the document where the error occurred. An error handler can use these arguments for any purpose it desires. A typical error handler might display the error message to the user, log it somewhere, or force the error to be ignored. setTimeout( ) setTimeout( ) call would be removed from splay_time_in_status_line( ) method, and we'd remove the onload . In this case, the di In addition to those three arguments, the return value of the onerror handler is significant. Browsers typically display an error message in a dialog box or in the status line when an error occurs. If the onerror handler returns true, it tells the system that the h necessary -- in other words, the system should not display its own error message. For example, if you do not want your users to be pestered by error messages, no matter how buggy the code you write is, you ke this at the start of all your JavaScript programs: very difficult for users to give you feedback when your ing error messages. onerror handler in Example 14-1 andler has handled the error and that no further action is could use a line of code li self.onerror = function( ) { return true; } Of course, doing this will make it programs fail silently without produc We'll see a sample use of an . That example uses the handler to display the error details to the use w the user to submit a bug Note that the onerror error handler port JavaScript 1.5 have an alternative means of catching and handling errors, however: they can use the onerror r and allo report containing those details. is buggy in Netscape 6. Although the function you specify is triggered when an error occurs, the three arguments that are passed are other browsers that supincorrect and unusable. Netscape 6 and try/catch statement. (See Chapter 6 for details.) 13.6 The Navigator Object The Window.navigator property refers to a Navigator object that contains information about the web browser as a whole, such as the version and a list of the data formats it can display. The Navigator object is named after Netscape Navigator, but it is also supported by Internet Explorer. IE also supports clientInformation as a vendor-neutral synonym for navigator. Unfortunately, Netscape and Mozilla do not support this property. The Navigator object has five main properties that provide version information about the browser that is running: appName The simple name of the web browser. appVersion The version number and/or other version information for the browser. Note that this should be considered an "internal" version number, since it does not always correspond to the version number displayed to the user. For example, Netscape 6 [...]... multiple windows or frames Recall that frames within a window are represented by Window objects; JavaScript makes little distinction between windows and frames In the most interesting applications, there is JavaScript code that runs independently in each of several windows The next section explains how the JavaScript code in each window can interact and cooperate with each of the other windows and with... with are the same as frames created with and Everything discussed here applies to both kinds of frames Figure 13-4 illustrates these relationships between frames and shows how code running in any one frame can refer to any other frame through the use of the frames, parent, and top properties The figure shows a browser window that contains two frames, one on top of the other... that window itself For frames that are direct children of a top-level window, the top property is the same as the parent property Frames are typically created with and tags In HTML 4, however, as implemented in IE 4 and later and Netscape 6 and later, the tag can also be used to create an "inline frame" within a document As far as JavaScript is concerned, frames created with... thing is possible with frames Any frame in a window can refer to any other frame through the use of the frames, parent, and top properties of the Window object Every window has a frames property This property refers to an array of Window objects, each of which represents a frame contained within the window (If a window does not have any frames, the frames[ ] array is empty and frames. length is zero.)... these methods allow us to open and close windows, control window position and size, request and relinquish keyboard focus, and scroll the contents of a window We conclude with an example that demonstrates several of these features 13.8.1 Opening Windows You can open a new web browser window with the open( ) method of the Window object This method takes four optional arguments and returns a Window object... creates a new window with that name and loads the specified URL into it The target and name attributes are part of HTML and operate without the intervention of JavaScript, but there are also JavaScript-related reasons to give names to your frames We've seen that every Window object has a frames[ ] array that contains references to each of its frames This array contains all the frames in a window (or frame),... bottom) itself contains three subframes, side by side Figure 13-4 Relationships between frames With this understanding of the relationships between frames, you may want to revisit Example 13-6, paying particular attention this time to the way the code (which is written to run in a second frame) refers to the history and location properties of the first frame 13.11.2 Window and Frame Names The second, optional... important reason to specify names for windows and frames is that those names can be used as the value of the target attribute of the , , and tags This value tells the browser where you want to display the results of activating a link, clicking on an image map, or submitting a form For example, if you have two windows, one named table_of_contents and the other mainwin, you might have... argument to open( ) is a list of features that specify the window size and GUI decorations If you omit this argument, the new window is given a default size and has a full set of standard features: a menu bar, status line, toolbar, and so on On the other hand, if you specify this argument, you can explicitly specify the size of the window and the set of features it includes For example, to open a small,... frame However, the code from both frames is executed by the same JavaScript interpreter, in the same JavaScript environment As we've seen, one frame can refer to any other frame using the frames, parent, and top properties So, although JavaScript code in different frames is executed with different scope chains, the code in one frame can still refer to and use the variables and functions defined by code . these methods allow us to open and close windows, control window position and size, request and relinquish keyboard focus, and scroll the contents of a window you feedback when your ing error messages. onerror handler in Example 14-1 andler has handled the error and that no further action is could use a line of

Ngày đăng: 05/10/2013, 13:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan