reptile7's JavaScript blog
Sunday, June 26, 2005
Properties III: More on Text and Links
Blog Entry #14

The last entry was devoted largely to the document object's 'global' properties - by that I mean those properties that pertain to the document as a whole. However, it follows from our discussion of the document anchors, forms, and links properties that all of a document body's elements are also document properties*; indeed and relatedly, you may have noticed at JavaScript Kit's document object page a document "all" property, "an IE4+ exclusive array that contains all of the elements within the document". Moreover, our ability to access and style document body elements via the getElementById( ) method, which we discussed in Blog Entry #8, implies that these elements are document properties.

*April 2017 Update: To clarify, the individual elements of a document can all be accessed in a property-like way and they do constitute nodes of the document in a modern-day DOM sense, but they are not actually properties of the classical JavaScript document object.

We have also noted that document body elements can themselves be JavaScript objects, and it is their properties that we now address. Specifically, in this and the next entries we will go over some of the properties of the <body> elements that Weekend Silicon Warriors deal with most often when writing HTML: text, links, images, and forms.

Formatting text on the fly: the style object, revisited

OK, so we can change a document's text color via the document fgColor property. But of course, we here at reptile7's JavaScript blog aren't satisfied with that; we want to be able to change dynamically all of the basic font properties, including:
• font typeface (e.g., Arial, Courier New, Georgia, etc.)
• font size
• font style (bold, italics, underline)

While I'm on this topic, I should mention that the HTML <font> element - the classic tool for setting font typeface, size, and color - is now deprecated, as is the underlining <u> element. (The boldening <b> and italicizing <i> elements, however, are still acceptable.) Now, we're all supposed to set these things using style sheets, and CSS is in fact the key to setting them on the fly with JavaScript.

At this point, you are probably thinking to yourselves, "Well, then, we should be able to set font properties by using the getElementById( ) method and the JavaScript DOM style object and by applying the method that we followed in Blog Entry #8 for setting text background colors," and you would be spot on. Let's begin with an example, followed by its code, and then we can summarize.

The quick brown fox jumps over the lazy dog.

Click on the buttons below to style dynamically the sentence above.

The code for this is:
<span id="fox">The quick brown fox jumps over the lazy dog.</span><br>
Click on the buttons below to style dynamically the sentence above.<br>
<input type="button" value="Change the Font Typeface" onclick="document.getElementById('fox').style.fontFamily='verdana';"><br>
<input type="button" value="Double the Font Size" onclick="document.getElementById('fox').style.fontSize='24pt';"><br>
<input type="button" value="Bolden It" onclick="document.getElementById('fox').style.fontWeight='bold';"><br>
<input type="button" value="Italicize It" onclick="document.getElementById('fox').style.fontStyle='italic';"><br>
<input type="button" value="Underline It" onclick="document.getElementById('fox').style.textDecoration='underline';"><br>
<input type="button" value="Change Its Color" onclick="document.getElementById('fox').style.color='forestgreen';">

In summary, the general approach here is:
(1) Put the text to be formatted in a paragraph, span, or division element, i.e., surround it with opening and closing HTML <p>, <span>, or <div> tags.
(2) Put an id="whatever" attribute in the opening <p>, <span>, or <div> tag.
(3) Choose some other body element to 'trigger' the text formatting - I used a form button, but any element will do.**
(4) Add an onClick or onMouseOver event handler to the opening HTML tag of the triggering element; to onClick or onMouseOver, assign the following general command:

document.getElementById('whatever').style.fontProperty='suitable_value'; (where fontProperty is fontFamily, fontStyle, fontSize, etc.)

in which document.getElementById('whatever') references the text element whose style/CSS attribute we are changing.

(**Yes, I realize that we can use the text element itself to trigger the formatting by putting the onclick/onmouseover attribute directly in the <p>, <span>, or <div> tag, but I prefer the 'remote control' method outlined above.)

In the name of completeness, I should bring to your attention that JavaScript also has string formatting methods that can be used to style text. For example:

document.write( ("The rain in Spain falls mainly on the plain.").italics( ) );

The rain in Spain falls mainly on the plain.

Link properties

As noted at DevGuru's Link object page, Link objects are Location objects and have the same properties as do Location objects, so it is fitting, in light of the brief treatment of Location object properties in HTML Goodies' JavaScript Primers #7, that we discuss Link object properties here.

OK, so we can change the color of unvisited links, active links, and visited links via the document linkColor, alinkColor, and vlinkColor properties, respectively. But it gets more interesting than that. HTML Goodies' JavaScript Objects Keyword Reference page tells us that "the Link object can also be used to define new links". To see how we can do this, let's first look at the anatomy of a hyperlink, which in most cases can be generalized as:

<a href="protocol//hostname/pathname">link text</a>

in which protocol, hostname, and pathname are properties of the Link object and represent the constituent parts of the target anchor URL. (A more complete URL anatomy appears at DevGuru's Link object page.)

Let's suppose that you author a Web page on which the first document link is:

<a href="">Click here to read The Story of Blogger.</a>

document.links[0].protocol will return:  http:
document.links[0].hostname will return:
document.links[0].pathname will return:  /about
document.links[0].href, which we discussed at the end of Blog Entry #13, will return:

OK, so we can read these properties. But I find that hostname, pathname, and href are all writable properties, and it wouldn't surprise me if the other URL-related Link properties (protocol, host, etc.) can be written as well. Let's illustrate with a couple of examples, shall we?

(1) Writing the hostname property

Do you prefer the Yahoo! or Google search engine? Indicate your choice by clicking on the appropriate button below.
Follow this link to your preferred search engine.

The code for this is:
Do you prefer the Yahoo! or Google search engine? Indicate your choice by clicking on the appropriate button below.<br>
<input type="button" value="Yahoo!" onclick="document.getElementById('presea').hostname='';">
<input type="button" value="Google" onclick="document.getElementById('presea').hostname='';">
<a href="http://" id="presea">Follow this link to your preferred search engine.</a>

(Due to the large and varying number of links on this page, it's much easier to access the link above by a document.getElementById('linkID') reference than by a document.links[i] reference.)

(2) Writing the pathname property

Which section of CNN interests you most? Indicate your choice by clicking on the appropriate button below.
Follow this link to your preferred CNN section.

The code for this is:
Which section of CNN interests you most? Indicate your choice by clicking on the appropriate button below.<br>
<input type="button" value="Politics" onclick="document.getElementById('precnn').pathname='/POLITICS/';">
<input type="button" value="Health" onclick="document.getElementById('precnn').pathname='/HEALTH/';">
<input type="button" value="Law" onclick="document.getElementById('precnn').pathname='/LAW/';">
<input type="button" value="Education" onclick="document.getElementById('precnn').pathname='/EDUCATION/';">
<a href="" id="precnn">Follow this link to your preferred CNN section.</a>

The Link href property can be set dynamically in an analogous manner.

Finally, DevGuru lists two non-URL-related link properties, target and text.

The target property names the window in which a clicked link (more precisely, the target anchor to which the link points) opens. If you were to code n documents and display them in separate windows - we'll discuss the opening of new windows with JavaScript in Primer #11 - or if your n documents are loaded into a collection of frames constituting the current window, then a link in one window/frame can be targeted to any of the other windows/frames via a target="window_or_frame_name" attribute in the link's <a> tag. (Joe discusses the targeting of links in frames here.) According to DevGuru's Link target property page, the target property is read/write, i.e., a command can either return the value of a preset target attribute or set a new target for a given link.

The text property refers to the Link object text that appears between the opening and closing anchor tags. The Link text property is not supported by MSIE, as noted by IRT (somewhat confusingly, IRT conflates the Link and Anchor objects on a single Anchor object page), and is read-only (or at least my attempts to write it were unsuccessful). BTW, for a link containing an image

<a href=""><img src="some_image.gif"></a>

the link_reference.text return is blank.

We'll discuss the properties of Image and Form objects in the next entry.


Sunday, June 19, 2005
Properties II: The Document Object
Blog Entry #13

(1) HTML Goodies' JavaScript Primers #7
(2) DevGuru's document object page
(3) JavaScript Kit's document object page
(4) IRT's document object page

We continue our JavaScript property odyssey by turning to the document object. In HTML Goodies' JavaScript Primers #7, Joe lists and gives definitions for thirteen document object properties:

bgColor, fgColor, linkColor, alinkColor, vlinkColor, location, referrer, title, lastModified, cookie, anchors, forms, links

Joe demonstrates the first nine of these properties in the Primer #7 script, which reads them, returning their values. Of this group, the bgColor, fgColor, linkColor, alinkColor, vlinkColor, location, and title properties are in fact read/write, whereas the referrer and lastModified properties are read-only.

The first five properties are analogous to familiar-but-now-mostly-deprecated attributes of the document <body> element:

Document Property     Corresponding <body> Attribute

We discussed and demonstrated the document bgColor property in Blog Entry #8. Also, here is a page that demonstrates the document fgColor property. (Here at Blogger, my use of a document.fgColor command will change the color of the reptile7's JavaScript blog title at the top of the page but not the color of the post text, which is part of a div element and is thus not "foreground" text.) I leave it to you to devise your own demos for the linkColor, alinkColor, and vlinkColor properties.

The document location property, according to the HTML Goodies' JavaScript Properties Keyword Reference page, returns the URL of the current document and is "read-only". I nonetheless find that I am able to write this property when using either MSIE or Netscape, i.e., I can use a document.location command to set up a link, much like the parent.location command that we discussed in Blog Entry #10. Try it out below:

The code for the button is:
<input type="button" value="Click Here to See the document.location Property in Action" onclick="document.location='#doclocDiv';">

However, the folks at Netscape say: "Location is not a property of the document object; its equivalent is the document.URL property. The document.location property, which is a synonym for document.URL, is deprecated." Hmmm...I was wondering why neither DevGuru, nor JavaScript Kit, nor IRT lists a location property at its document object page (they all list a URL property) would seem, then, that the window.location command is a better choice for setting up a link or for returning the URL of the current page than is the document.location command.

In the name of completeness: in comparing the document.location and document.URL expressions, I find that they are indeed both writable and return the same values when using MSIE; with Netscape, in contrast, document.location is writable but document.URL is read-only, although they read identically.

For the document referrer property, which as noted above is read-only, DevGuru provides the best and most precise definition: "If a destination document [the one you're currently looking at] is reached by a user clicking on a Link object [a hyperlink] in another document (the referrer), this property returns the referring document's URL." The document.referrer command does not simply return the URL of the Web page that you were at prior to the current page. If you arrive at the current page in some way other than clicking a link on the preceding page, for example:
(a) you typed the URL of the current page into the browser's address bar and then hit the return/enter key; or
(b) perhaps the current page is a bookmark and you accessed it via the Favorites/Bookmarks menu; or
(c) maybe you are reaccessing the current page via the Back button on the browser's toolbar after following a link on the current page, etc.;
then, as Joe notes, "no [referring] page is [document.referrer] returns a blank space."

BTW, JavaScript makes a distinction between a Link object, representing a source anchor element whose <a> tag holds a href="" attribute, and an Anchor object, which represents a target anchor element whose <a> tag holds a name="codeword" attribute.

Primer #7's definition of the document title property - "[it] returns the text between the HTML document's TITLE [element tags]" - suggests that it is read-only (as does its definitions in the HTML Goodies JavaScript Properties Keyword Reference and at DevGuru). However, JavaScript Kit correctly notes that the title property is "read/write in modern browsers", as we can see from the demo below:

Roll your mouse over these words to change the page title.

(The code for this is...ah, I'm sure that you can write it out by now.)
One might think that because status is a property of the window object, as was noted in Primer #4, then title would be a property of the window object; evidently not.

Like the title property, the document lastModified property, which "returns to the date the page was last modified", is fairly self-explanatory; according to DevGuru's lastModified page, the value of lastModified is usually taken from the HTTP header that is sent to the user by the server hosting the document. When was this page last modified? Roll your mouse over these words to find out.

Now, what about those last four properties - cookie, anchors, forms, and links? According to Joe, "examples of [these] would be above your heads at this point." I'm not so sure I any case, they still deserve some comment.

The cookie property of the document object is read/write. A document can use the document.cookie command to write a cookie to the user's hard disk or to retrieve the name/value information of cookies that have been set previously by (more precisely, are associated with) that same document. We will discuss the setting and retrieval of cookies in more detail in Script Tips #60-64.

Finally, the anchors, forms, and links properties of the document object represent built-in arrays of document body elements and they refer to these elements in JavaScript expressions. Much like the relationship between the Plugin object and the navigator object that we discussed in Blog Entry #12, Anchor, Form, and Link are again themselves JavaScript objects, with their own properties.

The anchors, forms, and links properties are a subset of a larger group of property/object arrays that are listed under "Document Collections" at IRT's document object page.

(Strangely, Joe does not bring up built-in arrays until Primer #26 - see the "Here's a little more on arrays:" subsection thereof. FWIW, the built-in frames array of the window object crops up in Joe's "So You Want To Change More Than One Frame, Huh?" tutorial.)

I do a lot of linking on this blog, so let's wrap up this entry with a couple of demos for the document links property.

(1) How many links does this page have? Roll your mouse over this sentence to find out.

The code for the demo sentence is:
<span style="color:brown;" onmouseover="window.alert('This page has ' + document.links.length + ' links.');">Roll your mouse over this sentence to find out.</span>

As you can deduce, length is a property that returns the size of the links array of the document. We'll see other uses of the length property in due course.

(2) Where does the first link on this page point to? Roll your mouse over this sentence to find out.

The code for the demo sentence is:
<span style="color:blue;" onmouseover="window.alert('The first link on this page points to: ' + document.links[0].href);">Roll your mouse over this sentence to find out.</span>

The 0 in square brackets is an index number for the referenced link as it appears in the flow of the document. Remembering that JavaScript begins counting at 0 (as noted in Blog Entry #6), the first link on the page is referenced as document.links[0], the second link is document.links[1], the third link is document.links[2], etc. In turn, href is a property that returns, in this case, the value of the href attribute of the <a> element that corresponds to the document's first Link object, i.e., the URL of the first link, as you would expect.

The document.location demo target anchor

Welcome to the document.location demo div.

Click here to return to the post's "The document location property... " paragraph.

In the previous entry, I complained that "there is no mention [in Primer #7] of the properties relating to text, image, and form elements". Of course, that doesn't mean that WE can't take a look at some of these properties, and we'll do that in the next post.


Saturday, June 11, 2005
Properties I: The Navigator Object
Blog Entry #12

In Blog Entry #2, we stated that JavaScript properties, as a part of speech, are the "adjectives" of JavaScript; we know now that they describe or modify JavaScript objects.

Some JavaScript properties are "read/write", i.e., we can both get (read) and set (write) their values; others are "read-only". Some JavaScript properties are highly useful; others are of marginal value.

Joe Burns' treatment of JavaScript properties in HTML Goodies' JavaScript Primers #7 leaves room for improvement. With respect to the four JavaScript objects that appear in the first six primers - document, Date, window, and Location - only document and Location properties are discussed in Primer #7. Disappointingly, there is no mention of the properties relating to text, image, and form elements.

Primer #7 also introduces two new objects, the JavaScript navigator and History objects, and discusses some of their properties.

HTML Goodies' JavaScript Properties Keyword Reference page is here. DevGuru's master list of JavaScript properties appears here.

Primer #7 begins with the navigator object, as will we. The navigator object is a host object that represents the user's browser; it was apparently named after the Netscape Navigator browser back in the day when Netscape was the dominant browser.

There is seemingly conflicting information on the Web as to where the navigator object fits in the JavaScript object hierarchy, which we'll discuss in Primer #8. Some Web sites put the navigator object at the top and/or outside of the hierarchy; others state that navigator is a property of the window object. My experience supports the latter view; the attempted execution of navigator.window commands (e.g., navigator.window.document.bgColor = "blue") on my computer gives only errors, but window.navigator.relevant_property operations all work OK.

The properties of the navigator object return information about the user's platform; these properties are all read-only. Primer #7 lists and defines four navigator properties: appName, appVersion, appCodeName, and userAgent. DevGuru's navigator object page lists these four plus four others; JavaScript Kit's navigator object page lists these four plus seven others.

Note that JavaScript Kit's navigator object page features a browser/operating system selection list ("Additional browsers' Navigator Information") whose individual options each pop up a display giving the relevant values of the basic navigator properties for that option. At first glance, much of this information seems suspect, for lack of a better word. For example, all of the listed browsers - all fifteen of them - return the same code name (appCodeName value), "Mozilla", which was the code name of the original Netscape browser. In addition, only one browser, Opera 7.5 (Identify as Opera), gives a return for the appVersion property - "7.50 (Windows NT 5.1; U)" - that one would reasonably expect. The browser that I use most often, Internet Explorer 5.1.6 for the Macintosh, gives as its version:

appVersion: 4.0 (compatible; MSIE 5.0; Macintosh; I; PPC)

- needless to say, this is not what I would have anticipated. However, in many (but not all) cases, the browser version does appear in the string returned by the userAgent property. Lastly, even the seemingly straightforward appName property returns the name "Netscape" for the Firefox, Safari, Mozilla, and AOL browsers.

The main application of the navigator object seems to be its use in browser-detection scripts that determine the name and version of the user's browser and/or whether the user is using a PC or a Mac, and then either (a) sends the user to a page whose coding is specifically designed for the user's system, or more likely, (b) pops up a window with a "Sorry, but you cannot access the desired content because you do not meet the necessary system requirements" type of message. Two such scripts are discussed in the HTML Goodies JavaScript Script Tips; they respectively span Script Tips #10-12 and #13-15. Moreover, according to the Wikipedia references linked above, the reason why "Mozilla" appears in the identifying information of non-Netscape browsers is to prevent browser-detection scripts from rerouting users of those browsers away from designed-for-Netscape Web pages.

The user's platform information can be extracted from the returns of navigator properties using methods of the JavaScript String object - this is a can of worms that we can open when we look at the script tips cited above.

Of course, use of a browser-detection script implies that a Webmaster is creating specific or separate content for Netscape vs. MSIE, or for newer versions of a browser vs. older versions, or for a PC vs. a Mac, etc., to which I say, "Ugh". We would all be better off, IMHO, if we coded in the spirit of the Viewable with Any Browser campaign: "One World, One Internet, One Standard".

One World, One Internet, One Standard

Two of the more interesting navigator properties, plugins and mimeTypes, frustratingly violate the above concept; they are supported by Netscape for both Windows and Mac users, and are supported by MSIE 5+ for Mac users, but they are not supported by MSIE for Windows users (as noted here for the plugins property, and I am assuming the same is true for the mimeTypes property). Plugin and MimeType themselves are JavaScript objects, with their own properties; they can be used to determine if your browser can handle a given file or media type.

I'm a bit hesitant to illustrate the plugins and mimeTypes properties/objects because of their lack of general usability, but hey, why not? At the risk of getting seriously ahead of ourselves, the following code (a for loop, an array, oh my...) can be used to print out the plugins that your browser has at its disposal:

<script type="text/javascript">
document.write("What plugins does your browser use to extend its functionality?");
for (i = 0; i < navigator.plugins.length; i ++) {
document.write("<br>(" + i + ") " + navigator.plugins[i].name); }

The output on my computer when using MSIE 5.1.6 is:
What plugins does your browser use to extend its functionality?
(0) Default Plugin
(1) Digital Rights Management Plugin
(2) MRJ Java Plugin
(3) RealPlayer(tm) G2 LiveConnect-Enabled Plug-in (Mac)
(4) Shockwave Flash
(5) Windows Media Plugin
(6) QuickTime Plug-in 5.0.2

(Again, this script probably won't work for the MSIE/Windows folks, but the rest of you might give it a shot.)

As you can see from JavaScript Kit's navigator object page, the language-related properties of the navigator object - e.g., language, systemLanguage, and userLanguage - are also browser-specific. But at least the cookieEnabled property, which returns true if the browser is set to accept cookies and false if it isn't, is browser-independent.

That'll do it for the navigator object and its properties. Internet Related Technologies lists some additional navigator properties that are not covered above, but I think we're good to go for the time being. Next up: the properties of the document object, which we'll get into in the following post.


Saturday, June 04, 2005
The Prompt( ) Method
Blog Entry #11

The event handlers of HTML Goodies' JavaScript Primers #4 and #5 have given us our first taste of the interactive capabilities of JavaScript. Primer #6, which we address today, continues in an interactivity vein with the introduction of the prompt( ) method of the window object. You will recall that the Primer #4 assignment introduced the alert( ) method, which pops up a box with a message for the user. The prompt( ) method similarly pops up a box with a message, but unlike an alert box, a prompt box also, fittingly, 'prompts' the user for input that can be put to use in a separate command statement.

Primer #6's other main topic, JavaScript variables, was discussed previously in Blog Entry #5, so I won't belabor it here.

Let's get on with the prompt( ) method. On the aforementioned prompt box are four features:
(1) a message or query for the user;
(2) a text box-like field, for user input, which can have an initial "value" (message) if desired;
(3) an "OK" button in the lower-right-hand corner; and
(4) a "Cancel" button to the left of the "OK" button.

The basic syntax for popping up a prompt box is:

window.prompt("message or query for the user");

(As noted at the very end of Blog Entry #7, methods and properties of the window object do not need to reference the window object, and you will often see the command above written as: prompt("message or query for the user");.)

Text can be put in the user input field via a second prompt( ) subparameter, with a comma delimiting the two subparameters:

window.prompt("message or query for the user", "text in the user input field");

The second prompt( ) subparameter is optional. Contra the "The Prompt Command" section of the primer, it is not necessary to include a second set of quotes, and the box will not read "undefined" as a result.

Roll your mouse over these words for a demo.

On my computer, when using MSIE, the prompt box user input field, although not visually highlighted, is nonetheless 'selected' in the sense that pressing the delete key will clear it, replacing the text with focus in the form of a blinking vertical line (a.k.a. an insertion point cursor). Netscape, in turn, pops up a prompt box with a blinking vertical line already appearing at the end of the text in the user input field. (If the second prompt( ) subparameter is left out, then the prompt box pops up with only an insertion point cursor in the user input field, whether using MSIE or Netscape.)

The Primer #6 Script

Primer #6's focal point is the script below:

<script type="text/javascript">
/* This script is intended to take information
from the user and place it upon the page */

var user_name = prompt ("Write your name in the box below","Write it here");
document.write("Hello " + user_name + ". Welcome to my page!");


After an introductory comment (we discussed commenting in JavaScript in Blog Entry #6), the script pops up a prompt box that asks for the user's name. The user deletes the "Write it here" text in the user input field and then types in a name. If and when the user clicks the "OK" button on the prompt box (we'll get to the "Cancel" possibility shortly), then the inputted user name is assigned, as an 'output', to the variable "user_name".

Subsequently, the document.write( ) statement makes use of the "user_name" variable, splicing it, as a subparameter, with two text strings in order to write "Hello name-inputted-by-user. Welcome to my page!" on the page.

(The Primer #3 script featured a document.write( ) statement that acted on variable-containing commands, but this is the first time we have seen a variable by itself appear in the write( ) parameter.)

It's not necessary to variabilize the output of the prompt command. Joe could have written:

document.write("Hello " + prompt("Write your name in the box below","Write it here") + ". Welcome to my page!");

Use of a variable makes the code a bit easier to follow, however.

If the user clears the input field and clicks "OK" without entering a name, then the output does not contain "null" but simply reads:

Hello . Welcome to my page!

however, if the user responds to the prompt box by clicking the "Cancel" button, then the output is indeed:

Hello null. Welcome to my page!

"Null" is a JavaScript reserved word and can be classified as a data type; it is roughly synonymous with "empty". If a variable has the value "null", then it has no value, or more precisely, it has a valid "value of no value". (A "null" variable thus has a more definite status than does an "undefined" variable, which in a script appears as a placeholder but is otherwise characteristicless.) In this case, the prompt( ) method output, variabilized or not, has no value and is thus "null" when acted on by the document.write( ) command.

Let me lastly address something Joe says at the outset of the primer, in the "The Concept" section: "we're now back to creating full JavaScripts rather than just adding Events to HTML, so we'll need to once again start using the full <SCRIPT type="text/javascript"> to </SCRIPT> format." As we saw above, however, prompt( ) commands can definitely be assigned to event handlers. As a second example, consider the code below, which is patterned on the Primer #6 script and even includes the use of a variable:

<span onclick="var colour = window.prompt('What is your favorite color?','Enter a color here'); style.color = colour;">Click on this sentence to change its text color.</span>

Try it out:

Click on this sentence to change its text color.

(The Primer #6 script itself can be executed by an event handler, although the end result is a bit strange in that the document.write( ) output supersedes the rest of the page - click here to see it for yourself.)

The end-of-primer assignment and its answer

Joe asks the reader to 'deconstruct' a script that obtains the reader's first name and the date and then writes them, as part of a sentence, to the title bar of the browser window.

You will notice that the script does not execute as advertised, i.e., the title bar reads "Assignment 6", and not "Hi name-inputted-by-user  Today's date is m/d/y  Thanks for coming". Why might this be?

Check the source code of Joe's "Assignment 6" page. Near the top, we have:

<TITLE>Assignment 6</TITLE>

On my computer, the needed corrective action is browser-dependent. When using MSIE, if I delete the "Assignment 6" between the <title> tags (so that nothing or only whitespace is there), or remove this line altogether, then the script works fine. Netscape requires me to remove the entire line.

In the answer, Joe notes that "this script must go above the BODY command in the HTML document, because that's where the TITLE goes." Up to this point, we haven't said anything about whether a given JavaScript script should be placed in the <head> or the <body> part of the document - oftentimes, it doesn't matter, and this is one of those times. Checking the source code once again, we see that the Assignment 6 page has neither <head> nor <body> tags. But the important thing, as we just noted, is to get rid of the "Assignment 6" title, which overrides the <title> commands of the script.

The scripting of the Assignment 6 page is noteworthy in other ways:

(1) In the main script, we see the returns of two different commands assigned to the same variable name, "d". The second statement creates a new Date object and assigns it to "d". Three statements later, the d.getDate( ) return is in turn assigned to "d". After the fifth statement, "d" in the script represents not the Date object but the new Date( ).getDate( ) return. Needless to say, the use of "d" here is algebraically unsatisfying (or at least I find it to be), but it is legitimate in JavaScript for a script to utilize a given variable name more than once in this manner.

(2) In extension of the main script, Joe sprinkles the user's name throughout the page text with the code:

<SCRIPT>document.write("" +name+ "")</SCRIPT>

Presumably, the quotes in the write( ) parameter are there to ensure that the "name" variable is recognized as a text string by the document.write( ) command, but I found that I could remove the quotes and use:


without any problems. Anyway, what grabs my attention here is that the value of "name", once set in the main script, 'crosses over' to subsequent, separate scripts. Less importantly, we can also conclude that the browser will recognize and execute a JavaScript script even if the opening <script> tag lacks a language="javascript" or type="text/javascript" attribute. (I applied this to the main script, removing type="text/javascript" from its <script> tag, and it reran OK.) I have no idea if this is true for other types of scripts or not.

But speaking of "main" and "subsequent" scripts, it's possible for the entire page to be one big script, using the following code:

<script type="text/javascript">
var name = window.prompt("Please write in your first name");
var d = new Date( );
var y = d.getFullYear( );
var m = d.getMonth( ) + 1;
var d = d.getDate( );
var t = m + '/' + d + '/' + y + ' ';
document.write("Hi "+ name + " Today's date is " + t + "Thanks for coming");
document.write("Hi, " + name + ". We've been expecting you, etc.");

We see from the above that a script can straddle the head and body parts of a document - click here to see it in action.

Finally, some nitpicking about the script deconstruction on the answer page (the temptation is there to go through this line by line, but the points I would make have been already covered, directly or indirectly, above and in previous entries, so I'll limit myself to the following):

(a) The fifth bullet point (• See the "+ 1900" after the year?...) should be deleted; it refers apparently to an earlier version of the primer that used the now-deprecated getYear( ) method instead of the getFullYear( ) method.

(b) The sixth bullet point should read:
• See that "+ 1" at the end of the "m" variable? That's a trick that sets the year month to the correct count. It's a good idea to use it when you ask for the month.

Properties, properties, properties...they're the focus of HTML Goodies' JavaScript Primers #7, which we'll thrash out in our next episode.


Powered by Blogger

Actually, reptile7's JavaScript blog is powered by Café La Llave. ;-)