Archive for August, 2007

Best web hosting site - 144Part IIIDocument Objects ReferenceThe JavaScript version implemented in

Friday, August 24th, 2007

144Part IIIDocument Objects ReferenceThe JavaScript version implemented in a browser is not always a good predictor of core lan- guage features available for that browser. For example, while JavaScript 1.2 (as implementedby Netscape in NN4) included broad support for regular expressions, not all of those featuresappeared in Microsoft s corresponding JScript implementation in IE4. By the same token, Microsoft implemented try-catcherror handling in its JScript in IE5, but Netscape didn tinclude that feature until the Mozilla-based NN6 implementation of JavaScript 1.5. Therefore, the language version number is far less important than the browser version in determiningwhich language features are available for you to use. Core Language Standard ECMAScriptAlthough Netscape first developed the JavaScript language, Microsoft incorporated the languagein Internet Explorer 3. Microsoft did not want to license the Java name from its trademarkowner (Sun Microsystems), which is why the language became known in the IE environment asJScript. Except for some very esoteric exceptions and the pace of newly introduced features, thetwo languages are essentially identical. The levels of compatibility between browser brands for acomparable generation are remarkably high for the core language (unlike the vast disparities inobject model implementations discussed in Chapter 14). As mentioned in Chapter 2, standards efforts have been under way to create industry-wide recommendations for browser makers to follow (to make developers lives easier). The corelanguage was among the first components to achieve standard status. Through the Europeanstandards body called ECMA, a formal standard for the language has been agreed to and pub- lished. The first specification for the language, dubbed ECMAScript by the standards group, was roughly the same as JavaScript 1.1 in Netscape Navigator 3. The standard defines how various data types are treated, how operators work, what a particular data-specific syntaxlooks like, and other language characteristics. A newer version (called version 3) adds manyenhancements to the core language (version 2 was version 1 with errata fixed). You can viewthe current version of the ECMA-262 specification at http://www.ecma-international.org/. If you are a student of programming languages, you will find the document fascinating; if yousimply want to script your pages, you will probably find the minutia mind-boggling. Both Netscape and Microsoft have pledged to make their browsers compliant with the ECMAstandard. The vast majority of the ECMAScript standard has appeared in Navigator since version 3 and Internet Explorer since version 4. And, as new features are added to the ECMAstandard, they tend to find their way into newer browsers as well. The latest version ofECMAScript is version 3, which is supported in JavaScript 1.5 (Moz1) and JScript in IE6. Version 4 of ECMAScript is currently in the works, along with comparable implementations ofJavaScript (2.0) and JScript by The Mozilla Foundation and Microsoft, respectively. Embedding Scripts in HTML DocumentsScriptable browsers offer several ways to include scripts or scripted elements in your HTMLdocuments. Not all approaches are available in all versions of every browser, but you havesufficient flexibility starting with Navigator 3 and some versions of Internet Explorer 3. Whenyou consider that the vast majority of computer users are now using at least version 4browsers, it s safe to assume a core level of script support among Web users. Exceptions tothis rule include users who have specifically turned off scripting in their browsers, someorganizations that install browsers with scripting turned off, and users with physical disabili- ties who require specialized browsers. Note

JavaScriptEssentialsWhenever JavaScript is discussed in the context of (Web host music)

Friday, August 24th, 2007

JavaScriptEssentialsWhenever JavaScript is discussed in the context of the Webbrowser environment, it is sometimes difficult to distinguishbetween JavaScript the scripting language and the objects that youuse the language to control. Even so, it s important to separate thelanguage from the object model just enough to help you make impor- tant design decisions when considering JavaScript-enhanced pages. You may come to appreciate the separation in the future if you useJavaScript for other object models, such as server-side programming. All the basics of the language are identical. Only the objects differ. This chapter elaborates on many of the fundamental subjects aboutthe core JavaScript language raised throughout the tutorial (Part II), particularly as they relate to deploying scripts in a world in whichvisitors to your pages may use a wide variety of browsers. Along theway, you receive additional insights into the language itself. You canfind details about the JavaScript core language syntax in Part IV. JavaScript VersionsThe JavaScript language has its own numbering system, which is com- pletely independent of the version numbers assigned to browsers. Thelanguage s creator, Netscape, historically has had the most influenceon the numbering system. The first version, logically enough, was JavaScript 1.0. This was theversion implemented in Navigator 2 and the first release of InternetExplorer 3. As the language evolved with succeeding browser versions, the JavaScript version number incremented in small steps. InternetExplorer 6 and Mozilla-based browsers support JavaScript 1.5. Each successive generation of JavaScript employs additional languagefeatures. For example, in JavaScript 1.0, arrays were not developedfully, causing scripted arrays to not track the number of items in thearray. JavaScript 1.1 filled that hole by providing a constructor func- tion for generating arrays and an inherent lengthproperty for anygenerated array. 1313CHAPTER …In This ChapterHow to separate thelanguage from thedocument object modelWhere scripts go inyour documentsJavaScript languageversionsLanguage highlights for experiencedprogrammers …

Document ObjectsReference …In This PartChapter 13JavaScript EssentialsChapter 14Document (Dedicated web hosting)

Thursday, August 23rd, 2007

Document ObjectsReference …In This PartChapter 13JavaScript EssentialsChapter 14Document Object ModelEssentialsChapter 15Generic HTML ElementObjectsChapter 16Window and FrameObjectsChapter 17Location and HistoryObjectsChapter 18The Document and Body ObjectsChapter 19Link and Anchor ObjectsChapter 20Image, Area, and Map ObjectsChapter 21The Form and Related ObjectsChapter 22Button ObjectsChapter 23Text-Related Form ObjectsChapter 24Select, Option, and FileUpload ObjectsChapter 25Event ObjectsChapter 26Style Sheet and Style Objects …

140Part IIJavaScript TutorialExercises1.Explain the difference between (Database web hosting) a document

Wednesday, August 22nd, 2007

140Part IIJavaScript TutorialExercises1.Explain the difference between a document image object and the memory type of imageobject. 2.Write the JavaScript statements needed to precache an image file named jane.jpgthatlater will be used to replace the document image defined by the following HTML: people 3.With the help of the code you wrote for question 2, write the JavaScript statement thatreplaces the document image with the memory image. 4.Backward-compatible document image objects do not have event handlers for mouseevents. How do you trigger scripts needed to swap images for mouse rollovers? 5.Assume that a tableelement contains an empty table cell (td) element whose ID isforwardLink. Using W3C DOM node creation techniques, write the sequence of scriptstatements that create and insert the following hyperlink into the table cell: Next Page

139Chapter 12Images and Dynamic HTMLparagraph element belonging (Web design) to

Wednesday, August 22nd, 2007

139Chapter 12Images and Dynamic HTMLparagraph element belonging to a class called centeredwill be appended to a spanwhose IDis placeholder. Some of the text for the content of the paragraph comes from a text field in aform (the visitor s first name). Here is the complete sequence: var newElem = document.createElement( p ); newElem.className = centered ; var newText = document.createTextNode( Thanks for visiting, + document.forms[0].firstName.value); // insert text node into new paragraphnewElem.appendChild(newText); // insert completed paragraph into placeholderdocument.getElementById( placeholder ).appendChild(newElem); The W3C DOM approach takes a lot of tiny steps to create, assemble, and insert the piecesinto their destinations. After creating the element and text nodes, the text node must beinserted into the element node. Because the new element node is empty when it is created, the DOM appendChild()method plugs the text node into the element (between its start andend tags, if you could see the tags). With the paragraph element assembled, it then getsinserted at the end of the initially empty spanelement. Additional W3C DOM methods(described in Chapters 15 and 16) provide more ways to insert, remove, and replace nodes. Dynamic content via the innerHTML propertyPrior to the W3C DOM specification, Microsoft invented a property of all element objects: innerHTML. This property first appeared in IE4, and became popular due to its practicality. The property s value is a string containing HTML tags and other content, just as it wouldappear in an HTML document inside the current element s tags. Even though the W3C DOMworking group did not implement this property for the published standard, the propertyproved to be too practical and popular for modern browser makers to ignore. You can find itimplemented as a de facto standard in Mozilla-based browsers and Safari, among others. To show you the difference in the approach, the following code example shows the same con- tent creation and insertion as shown in the previous W3C DOM section, but this time with theinnerHTMLproperty: // accumulate HTML as a stringvar newHTML =

Thanks for visiting, ; newHTML += document.forms[0].firstName.value; newHTML +=

; // blast into placeholder element s contentdocument.getElementById( placeholder ).innerHTML = newHTML; While the innerHTMLversion seems more straightforward and it makes it easier for HTMLcoders to visualize what s being added the more code-intensive DOM node approach ismore efficient when the Body modification task entails lots of content. Extensive string con- catenation operations can slow down browser script processing. Sometimes the shortestscript is not necessarily the fastest. And so ends the final lesson of the JavaScript Bible, Fifth Editiontutorial. If you have gonethrough every lesson and tried your hand at the exercises, you are now ready to dive into therest of the book to learn the fine details and many more features of both the document objectmodel and the JavaScript language. You can work sequentially through the chapters of PartsIII and IV, but before too long, you should also take a peek at Chapter 45 on the CD-ROM tolearn some debugging techniques that help the learning process.

138Part IIJavaScript Tutorialhigher degree of dynamism is possible (Web hosting mysql)

Tuesday, August 21st, 2007

138Part IIJavaScript Tutorialhigher degree of dynamism is possible in your applications. Dynamic HTML is a very deepsubject, with lots of browser-specific peculiarities. In this final section of the tutorial, youwilllearn techniques that work in all W3C DOM-compatible browsers. I ll focus on two of themost common tasks for which DHTML is used: changing element styles and modifying Bodycontent. Changing stylesheet settingsEach element that renders on the page (and even some that don t) has a property calledstyle. This property provides script access to all Cascading Style Sheet (CSS) propertiessupported for that element by the current browser. Property values are the same as thoseused for CSS specifications frequently a different syntax than similar settings that used tobe made by HTML tag attributes. For example, if you wish to set the text color of a quote ele- ment whose ID is FranklinQuote, the syntax isdocument.getElementById( FranklinQuote ).style.color = rgb(255, 255, 0) ; Because the CSS colorproperty accepts other ways of specifying colors (such as the tradi- tional hexadecimal triplet #ffff00), you may use those as well. Some CSS property names, however, do not conform to JavaScript naming conventions. Several CSS property names contain hyphens. When that occurs, the scripted equivalent ofthe property compresses the words together and capitalizes the start of each word. Forexample, the CSS property font-weightwould be set in script as follows: document.getElementById( highlight ).style.fontWeight = bold ; A related technique puts more of the design burden on the CSS code. For example, if youdefine CSS rules for two different classes, you can simply switch the class definition beingapplied to the element by way of the element object s classNameproperty. For example, let ssay you define two CSS class definitions with different background colors: .normal {background-color: #ffffff} .highlighted {background-color: #ff0000} In the HTML page, the element first receives its default class assignment as follows:

A script statement can then change the class of that element object so that the highlightedstyle applies to it: document.getElementById( news ).className = highlighted ; Restoring the original class name also restores its look and feel. This approach is also a quickway to change multiple style properties of an element with a single statement. Dynamic content via W3C DOM nodesIn Chapter 8 you met the document.createElement()and document.createTextNode() methods. These methods create new DOM objects out of thin air, which you may then modifyby setting properties (attributes) prior to plugging the new stuff into the document tree forall to see. As an introduction to this technique, I ll demonstrate the steps you would go through toaddan element and its text to a placeholding spanelement on the page. In this example, a

137Chapter 12Images and (Free web design) Dynamic HTMLYou can see the

Monday, August 20th, 2007

137Chapter 12Images and Dynamic HTMLYou can see the results of this lengthy script in Figure 12-1. As the user rolls the mouse atopone of the images, it changes from a light to dark color by swapping the entire image. You canaccess the image files on the CD-ROM, and I encourage you to enter this lengthy listing andsee the magic for yourself. Figure 12-1:Typical mouse rollover image swapping. The javascript: Pseudo-URLYou have seen several instances in this and previous chapters of applying what is called thejavascript:pseudo-URL to hrefattributes of and tags. This technique shouldbe used sparingly at best, especially for public Web sites that may be accessed by users withnon-scriptable browsers (for whom the links will be inactive). The technique was implemented to supplement the onclickevent handler of objects that actas hyperlinks. Especially in the early scripting days, when elements such as images had noevent handlers of their own, hyperlinked elements surrounding those inactive elementsallowed users to appear to interact directly with elements such as images. When the intendedaction was to invoke a script function (rather than navigate to another URL, as is usually thecase with a hyperlink), the language designers invented the javascript:protocol for use inassignments to the hrefattributes of hyperlink elements (instead of leaving the requiredattribute empty). When a scriptable browser encounters an hrefattribute pointing to a javascript:pseudo- URL, the browser executes the script content after the colon when the user clicks on the ele- ment. For example, near the end of Listing 12-2, all four tags point to javascript: pseudo-URLs that invoke script functions on the page, such as Be aware that unless you override the status bar text with mouse event handlers (as shownin Listing 12-2), the pseudo-URL appears in the status bar for the user to see (and perhaps befrightened). More importantly, however, remember that this URL is to be used only for assign- ment to hrefattributes. Do not use it with event handlers. Popular Dynamic HTML TechniquesBecause today s scriptable browsers uniformly permit scripts to access each element of thedocument and automatically reflow the page s content when anything changes, a much

136Part IIJavaScript (Abyss web server) Tutorial// controller functions (disabled) function playIt()

Monday, August 20th, 2007

136Part IIJavaScript Tutorial// controller functions (disabled) function playIt() { } function stopIt() { } function pauseIt(){ } function rewindIt() { }


Jukebox Controls
I surround each image in the document with a link because the link object has the event han- dlers needed to respond to the mouse rolling over the area for compatibility back to NN3. Each link s onmouseoverevent handler calls the imageOn()function, passing the name of theimage object to be swapped. Because both the onmouseoverand onmouseoutevent handlersrequire a returntruestatement to work in older browsers, I combine the second functioncall (to setMsg()) with the returntruerequirement. The setMsg()function alwaysreturns trueand is combined with the returnkeyword before the call to the setMsg()func- tion. It s just a trick to reduce the amount of code in these event handlers. If you are typing this listing to try it out, be sure to keep each entire tag and its attributesin one unbroken line; or insert a carriage return beforeany event handler name.

Note

Abyss web server - 135Chapter 12Images and Dynamic HTML// off image array

Sunday, August 19th, 2007

135Chapter 12Images and Dynamic HTML// off image array — set off image path for each button offImgArray[ play ].src = images/playoff.jpg ; offImgArray[ stop ].src = images/stopoff.jpg ; offImgArray[ pause ].src = images/pauseoff.jpg ; offImgArray[ rewind ].src = images/rewindoff.jpg ; // precache all on button imagesvar onImgArray = new Array(); onImgArray[ play ] = new Image(75,33); onImgArray[ stop ] = new Image(75,33); onImgArray[ pause ] = new Image(75,33); onImgArray[ rewind ] = new Image(86,33); // on image array — set on image path for each button onImgArray[ play ].src = images/playon.jpg ; onImgArray[ stop ].src = images/stopon.jpg ; onImgArray[ pause ].src = images/pauseon.jpg ; onImgArray[ rewind ].src = images/rewindon.jpg ; } As you can see in the following HTML, when the user rolls the mouse atop any of the visibledocument image objects, the onmouseoverevent handler (from the link object surroundingthe image in the document) invokes the imageOn()function, passing the name of the particu- lar image. The imageOn()function uses that name to synchronize the document.imagesarray entry (the visible image) with the entry of the in-memory array of on images from theonImgArrayarray. The srcproperty of the array entry is assigned to the corresponding doc- ument image srcproperty. // functions that swap images & status barfunction imageOn(imgName) { if (document.images) { document.images[imgName].src = onImgArray[imgName].src; } } The same goes for the onmouseoutevent handler, which needs to turn the image off by invok- ing the imageOff()function with the same index value. function imageOff(imgName) { if (document.images) { document.images[imgName].src = offImgArray[imgName].src; } } Both the onmouseoverand onmouseoutevent handlers set the status bar to prevent the uglyjavascript:URL (described later) from appearing there as the user rolls the mouse atopthe image. The onmouseoutevent handler sets the status bar message to an empty string. function setMsg(msg) { window.status = msg; return true; } For this demonstration, I disable the functions that control the jukebox. But I leave the emptyfunction definitions here so they catch the calls made by the clicks of the links associatedwith the images.

Managed web hosting - 134Part IIJavaScript TutorialCreating image rolloversA favorite technique to

Saturday, August 18th, 2007

134Part IIJavaScript TutorialCreating image rolloversA favorite technique to add some pseudo-excitement to a page is to swap button images asthe user rolls the cursor atop them. The degree of change to the image is largely a matter oftaste. The effect can be subtle a slight highlight or glow around the edge of the originalimage or drastic a radical change of color. Whatever your approach, the scripting is thesame. When several of these graphical buttons occur in a group, I tend to organize the memoryimage objects as arrays and create naming and numbering schemes that facilitate workingwith the arrays. Listing 12-2 shows such an arrangement for four buttons that control a juke- box. The code in the listing is confined to the image-swapping portion of the application. Thisis the most complex and lengthiest listing of the tutorial, so it requires a bit of explanation asit goes along. Listing 12-2:Image Rollovers