Archive for July, 2007

Affordable web hosting - 90Part IIJavaScript TutorialYou can generally navigate to a

Sunday, July 22nd, 2007

90Part IIJavaScript TutorialYou can generally navigate to a page in your own Web site by specifying a relative URL (thatis, relative to the currently loaded page) rather than the complete URL with protocol andhost information. For pages outside of the domain of the current page, you need to specifythe complete URL. If the page to be loaded is in another window or frame, the window reference must be part ofthe statement. For example, if your script opens a new window and assigns its reference to avariable named newWindow, the statement that loads a page into the subwindow isnewWindow.location.href = http://www.dannyg.com ; The navigator ObjectDespite a name reminiscent of the Netscape Navigator branded browser, the navigatorobjectis implemented in all scriptable browsers. All browsers also implement a handful of propertiesthat reveal the same kind of information that browsers send to servers with each page request. Thus, the navigator.userAgentproperty returns a string text with numerous details aboutthe browser and operating system. For example, a script running in Internet Explorer 6 inWindows XP receives the following value for the navigator.userAgentproperty: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461) The same script running in Mozilla 1.4 on a Macintosh reveals the following userAgentdetails: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4) Gecko/20030624You have already used two other navigator properties (navigator.appVersionand navigator.appName) in your first script of Chapter 3. See Chapter 38 on the CD-ROM formore details about this object and the meaning of the values returned by its properties. Itwas once used extensively to branch script execution according to various browser ver- sions.Chapter 14 describes more modern ways to accomplish browser version detection. The document ObjectThe documentobject holds the real content of the page. Properties and methods of the docu- mentobject generally affect the look and content of the document that occupies the window. All W3C DOM-compatible browsers (and IE4) allow script access to the text con-tents of apage once the document has loaded. However, as you saw in your first script of Chapter 3, the document.write()method lets a script dynamically create content as the page loads onany browser. Many documentobject properties are arrays of other objects in the document, which provide additional ways to reference these objects (over and above the document.getElementById()method). Accessing a documentobject s properties and methods is straightforward, as shown in thefollowing syntax examples: [window.]document.propertyName[window.]document.methodName([parameters]) The windowreference is optional when the script is accessing the documentobject that con- tains the script. If you want a preview of the long list of documentobject properties of thebrowser you re using, enter documentinto the bottom text box of The Evaluator Jr. and pressEnter/Return. The object s properties and current values appear in the Results box. Followingare some of the most commonly used properties and methods of the documentobject.

89Chapter 8Window and Document ObjectsThe window.prompt()method (Dedicated web hosting) has two

Sunday, July 22nd, 2007

89Chapter 8Window and Document ObjectsThe window.prompt()method has two parameters. The first is the message that acts as aprompt to the user. You can suggest a default answer in the text field by including a string asthe second parameter. If you don t want any default answer to appear, include an emptystring (two double quotes without any space between them). This method returns one value when the user clicks either button. A click of the Cancel but- ton returns a value of null, regardless of what the user types into the field. A click of the OKbutton returns a string value of the typed entry. Your scripts can use this information in con- ditions for ifand if…elseconstructions. A value of nullis treated as falsein a condi- tion. It turns out that an empty string is also treated as false. Therefore, a condition caneasily test for the presence of real characters typed into the field to simplify a condition test, as shown in the following fragment: var answer = prompt( What is your name? , ); if (answer) { alert( Hello, + answer + ! ); } The only time the alert()method is called is when the user enters something into theprompt dialog box and clicks the OK button. onload event handlerThe windowobject reacts to several system and user events, but the one you will probablyuse most often is the event that fires as soon as everything in a page finishes loading. Thisevent waits for images, Java applets, and data files for plug-ins to download fully to thebrowser. It can be dangerous to script access to elements of a document object while thepage loads because if the object has not loaded yet (perhaps due to a slow network connec- tion or server), a script error results. The advantage of using the onloadevent to invokefunctions is that you are assured that all document objects are in the browser s documentobject model. Window event handlers are placed inside the tag. Even though you willcome to associate the tag s attributes with the documentobject s properties, it is thewindowobject s event handlers that go inside the tag. The location ObjectSometimes an object in the hierarchy represents something that doesn t seem to have thekind of physical presence that a window or a button does. That s the case with the locationobject. This object represents the URL loaded into the window. This differs from the docu- mentobject (discussed later in this lesson) because the document is the real content; thelocation is simply the URL. Unless you are truly Web-savvy, you may not realize a URL consists of many components thatdefine the address and method of data transfer for a file. Pieces of a URL include the protocol(such as http:) and the hostname (such as www.example.com). You can access all of theseitems as properties of the locationobject. For the most part, though, your scripts will beinterested in only one property: the hrefproperty, which defines the complete URL. Setting the location.hrefproperty is the primary way your scripts navigate to other pages: location.href = http://www.dannyg.com ;

88Part IIJavaScript TutorialThe appearance of this (Web site directory) and two

Sunday, July 22nd, 2007

88Part IIJavaScript TutorialThe appearance of this and two other JavaScript dialog boxes (described next) has changedsince the first scriptable browsers. In older browser versions (as shown in Figure 8-2), thebrowser inserted words clearly indicating that the dialog box was a JavaScript Alert. Different browsers display different title bars whose content cannot be altered by script. Youcan change only the other message content. All three dialog box methods are good cases for using a windowobject s methods without thereference to the window. Even though the alert()method is technically a windowobjectmethod, no special relationship exists between the dialog box and the window that generatesit. In production scripts, I usually use the shortcut reference: alert( This is a JavaScript alert dialog. ); window.confirm() methodThe second style of dialog box presents two buttons (Cancel and OK in most versions onmost platforms) and is called a confirm dialog box (see Figure 8-3). More importantly, this isone of those methods that returns a value: trueif the user clicks OK, falseif the user clicksCancel. You can use this dialog box and its returned value as a way to have a user make adecision about how a script progresses. Figure 8-3:A JavaScript confirm dialog box(IE6/WinXP style). Because the method always returns a Boolean value, you can use the evaluated value of theentire method as a condition statement in an ifor if…elseconstruction. For example, inthe following code fragment, the user is asked about starting the application over. Doing socauses the default page of the site to load into the browser. if (confirm( Are you sure you want to start over? )) { location.href = index.html ; } window.prompt() methodThe final dialog box of the windowobject, the prompt dialog box (see Figure 8-4), displays amessage that you set and provides a text field for the user to enter a response. Two buttons, Cancel and OK, enable the user to dismiss the dialog box with two opposite expectations: canceling the entire operation or accepting the input typed into the dialog box. Figure 8-4:A JavaScript prompt dialog box (IE6/WinXP style).

87Chapter 8Window and Document ObjectsWindow Properties and MethodsThe (Web host music)

Saturday, July 21st, 2007

87Chapter 8Window and Document ObjectsWindow Properties and MethodsThe one property and three methods for the windowobject described in this section have animmediate impact on user interaction. They work with all scriptable browsers. You can findextensive code examples in Part III for each property and method. You can also experimentwith the one-statement script examples by entering them in the top text box of The EvaluatorJr. (from Chapter 6). window.status propertyThe status bar at the bottom of the browser window normally displays the URL of a link whenyou roll the mouse pointer atop it. Other messages also appear in that space during docu- ment loading, Java applet initialization, and the like. However, you can use JavaScript to dis- play your own messages in the status bar at times that may be beneficial to your users. Forexample, rather than display the URL of a link, you can display a friendlier, plain-languagedescription of the page at the other end of the link (or a combination of both to accommo- date both newbies and geeks). You can assign the window.statusproperty some other text at any time. To change the sta- tus bar text of a link as the cursor hovers atop the link, you trigger the action with anonmouseoverevent handler of a link object. Due to the simplicity of setting the window.statusproperty, it is most common for the scriptstatements to run as inline scripts in the event handler definition. This is handy for shortscripts because you don t have to specify a separate function or add

Web site design and hosting - 85Chapter 8Window and Document ObjectsA windowobject also has

Saturday, July 21st, 2007

85Chapter 8Window and Document ObjectsA windowobject also has a synonym when the script doing the referencing points to the win- dow that houses the document. The synonym is self. Reference syntax then becomesself.propertyNameself.methodName([parameters]) You can use these initial reference object names interchangeably, but I tend to reserve theuse of selffor more complex scripts that involve multiple frames and windows. The selfmoniker more clearly denotes the current window holding the script s document. It makesthe script more readable by me and by others. Back in Chapter 4, I indicated that because the windowobject is always there when a scriptruns, you could omit it from references to any objects inside that window. Therefore, the fol- lowing syntax models assume properties and methods of the current window: propertyNamemethodName([parameters]) In fact, as you will see in a few moments, some methods may be more understandable if youomit the windowobject reference. The methods run just fine either way. Creating a windowA script does not create the main browser window. A user does that by virtue of launchingthe browser or by opening a URL or file from the browser s menus (if the window is notalready open). But a script can generate any number of subwindows once the main window isopen (and that window contains a document whose script needs to open subwindows). The method that generates a new window is window.open(). This method contains up tothree parameters that define window characteristics, such as the URL of the document toload, its name for targetattribute reference purposes in HTML tags, and physical appear- ance (size and chrome contingent). I don t go into the details of the parameters here (they recovered in great depth in Chapter 16), but I do want to expose you to an important conceptinvolved with the window.open()method. Consider the following statement that opens a new window to a specific size and with anHTML document from the same server directory that holds the current page: var subWindow = window.open( define.html , def , height=200,width=300 ); The important thing to note about this statement is that it is an assignment statement. Something gets assigned to that variable subWindow. What is it? It turns out that when thewindow.open()method runs, it not only opens up that new window according to specifica- tions set as parameters, but it also evaluates to a reference to that new window. In program- ming parlance, the method is said to return a value in this case, a genuine object reference. The value returned by the method is assigned to the variable. Your script can now use that variable as a valid reference to the second window. If you needto access one of its properties or methods, you must use that reference as part of the com- plete reference. For example, to close the subwindow from a script in the main window, usethis reference to the close()method for that subwindow: subWindow.close();

84Part IIJavaScript TutorialFigure 8-1:The (Web hosting domain names) top-level browser object model

Friday, July 20th, 2007

84Part IIJavaScript TutorialFigure 8-1:The top-level browser object model for all scriptable browsers. The window ObjectAt the very top of the object hierarchy is the windowobject. This object gains that exaltedspot in the object food chain because it is the master container for all content you view in theWeb browser. As long as a browser window is open even if no document is loaded in thewindow the windowobject is defined in the current model in memory. In addition to the content part of the window where documents go, a window s sphere ofinfluence includes the dimensions of the window and all of the stuff that surrounds the con- tent area. The area where scrollbars, toolbars, the status bar, and (non-Macintosh) menu barlive is known as a window s chrome. Not every browser has full scripted control over thechrome of the main browser window, but you can easily script the creation of additional win- dows sized the way you want and that have only the chrome elements you wish to display inthe subwindow. Although the discussion about frames comes in Chapter 11, I can safely say now that eachframe is also considered a windowobject. If you think about it, that makes sense becauseeach frame can hold a different document. When a script runs in one of those documents, itregards the frame that holds the document as the windowobject in its view of the object hierarchy. As you learn in this chapter, the windowobject is a convenient place for the document objectmodel to attach methods that display modal dialog boxes and adjust the text that displays inthe status bar at the bottom of the browser window. A windowobject method enables you tocreate a separate window that appears on the screen. When you look at all of the properties, methods, and event handlers defined for the windowobject (see Chapter 16), it should beclear why they are attached to window objects visualize their scope and the scope of abrowser window. Accessing window properties and methodsYou can word script references to properties and methods of the windowobject in severalways, depending more on whim and style than on specific syntactical requirements. The mostlogical and common way to compose such references includes the windowobject in thereference: window.propertyNamewindow.methodName([parameters]) windowdocumentnavigatorscreenhistorylocation

Web design company - Window andDocument ObjectsNow that you have exposure to

Friday, July 20th, 2007

Window andDocument ObjectsNow that you have exposure to programming fundamentals, itiseasier to demonstrate how to script objects in documents. Starting with this lesson, the tutorial turns back to the documentobject model, diving more deeply into each of the objects you willplace in many of your documents. Top-Level ObjectsAs a refresher, study the hierarchy of top-level objects in Figure 8-1. This chapter focuses on objects of this level that you ll frequentlyencounter in your scripting: window, location, navigator, anddocument. The goal is not only to equip you with the basics so youcan script simple tasks, but also to prepare you for in-depth examina- tions of each object and its properties, methods, and event handlersin Part III of this book. I introduce only the basic properties, methods, and event handlers for objects in this tutorial you can find farmorein Part III. Examples in that part of the book assume you knowthe programming fundamentals covered in previous chapters. 88CHAPTER …In This ChapterWhat the windowobject doesHow to access keywindowobjectproperties and methodsHow to trigger scriptactions after adocument loadsThe purposes of thelocationandhistoryobjectsHow the documentobject is createdHow to access keydocumentobjectproperties and methods …

X web hosting - 81Chapter 7Programming Fundamentals, Part II2.Examine the following function

Thursday, July 19th, 2007

81Chapter 7Programming Fundamentals, Part II2.Examine the following function definition. Can you spot any problems with the defini- tion? If so, how can you fix the problems? function format(ohmage) { var result; if ohmage >= 1e6 { ohmage = ohmage / 1e6; result = ohmage + Mohms ; } else { if (ohmage >= 1e3) ohmage = ohmage / 1e3; result = ohmage + Kohms ; elseresult = ohmage + ohms ; } alert(result); 3.Devise your own syntax for the scenario of looking for a ripe tomato at the grocerystore, and write a forloop using that object and property syntax. 4.Modify Listing 7-2 so it does not reuse the hisDogvariable inside the function. 5.Given the following table of data about several planets of our solar system, create aWeb page that enables users to enter a planet name and, at the click of a button, havethe distance and diameter appear either in an alert box or (as extra credit) in separatefields of the page. PlanetDistance from the SunDiameterMercury36 million miles3,100 milesVenus67 million miles7,700 milesEarth93 million miles7,920 milesMars141 million miles4,200 miles …

80Part IIJavaScript Tutorialis found. When the (Fedora web server) forloop breaks,

Thursday, July 19th, 2007

80Part IIJavaScript Tutorialis found. When the forloop breaks, the value of the icounter is fixed at the row of theUSStatesarray containing the entered state. I need that index value to find the correspond- ing entry in the other array. Even though the counting variable, i, is initialized in the forloop, it is still alive and in the scope of the function for all statements after the initialization. That s why I can use it to extract the value of the row of the stateEnteredarray in the finalstatement that displays the results in an alert message. This application of a forloop and array indexes is a common one in JavaScript. Study thecode carefully and be sure you understand how it works. This way of cycling through arraysplays a role not only in the kinds of arrays you create in your code, but also with the arraysthat browsers generate for the document object model. Document objects in arraysIf you look at the documentobject portions of the Quick Reference in Appendix A, you cansee that the properties of some objects are listed with square brackets after them. These are, indeed, the same kind of square brackets you just saw for array indexes. That s because whena document loads, the browser creates arrays of like objects in the document. For example, ifyour page includes two

tag sets, then two forms appear in the document. Thebrowser maintains an array of form objects for that document. References to those forms aredocument.forms[0] document.forms[1] Index values for document objects are assigned according to the loading order of the objects. In the case of formobjects, the order is dictated by the order of the
tags in the docu- ment. This indexed array syntax is another way to reference forms in an object reference. Youcan still use a form s identifier if you prefer and I heartily recommend using object nameswherever possible because even if you change the physical order of the objects in yourHTML, references that use names still work without modification. But if your page containsonly one form, you can use the reference types interchangeably, as in the following examplesof equivalent references to the length property of a form s elementsarray (the elementsarray contains all the form controls in the form): document.getElementById( entryForm ).elements.lengthdocument.forms[0].elements.lengthIn examples throughout this book, you can see that I often use the array type of reference tosimple forms in simple documents. But in my production pages, I almost always use namedreferences. Exercises1.With your newly acquired knowledge of functions, event handlers, and control struc- tures, use the script fragments from this chapter to complete the page that has thelookup table for all of the states and the years they entered into the Union. If you donot have a reference book for the dates, use different year numbers starting with 1800for each entry. In the page, create a text entry field for the state and a button that trig- gers the lookup in the arrays.