Thursday, May 26, 2005
Event Handlers, Act III
Blog Entry #10
highlighting of text characters in a text, textarea, or password form element with the mouse cursor. Consider, for example, the text box below; highlight with your mouse the "select me" text, and see what happens to it:
The coding for this is:
<input type="text" value="select me" onselect="style.fontVariant='small-caps';">
It's not necessary to select the entire box value to trigger the execution of the onSelect command; in fact, selecting just a single character will do it.
As far as I am aware, the onSelect event handler cannot be used with 'normal' text on a Web page; sure enough, my attempts to execute onSelect attribute commands in <p>, <span>, and <div> tags were unsuccessful.
In this section of the primer, Joe demonstrates the onSubmit event handler with a new command:
Joe's classification of "parent" as a property and of "location" as an object, while correct to an extent, is confusing and incomplete. Let's fill in the gaps, shall we?
HTML Goodies waits until Primer #9 to illustrate the onLoad event handler, but that doesn't mean we can't sneak in a demo here, does it now? Click here to see an onLoad command in action; close the resulting window to see an onUnload command in action.
(I was originally going to put onLoad and onUnload attribute commands in the <body> tag of my Blogger template in order to demonstrate these event handlers directly here on my blog, but I found that I am unable to execute independently onSubmit and onUnload commands on my computer, so I created a separate page for onLoad and onUnload. I refer you to the source of the demo page for the coding.)
onUnload is an event handler only for the window object. An unload event occurs upon 'closing' a Web page in one way or another, e.g., going to a new page in the same window, closing the page with the Close command under the File menu, or quitting the browser. It follows that an onUnload command executes when leaving a Web page, and the onUnload attribute - like window-related onFocus, onBlur, and onLoad attributes - is placed in the <body> tag. HTML Goodies waits until Primer #10 to illustrate the onUnload event handler, using it there with a window.alert( ) command, as does the demo above.
I'll wrap up this entry with a few remarks about...
The end-of-primer assignment and its answer
Joe asks the reader to create an 'interactive' form whose individual elements each make use of an event handler.
Let's first note that a form with a text box, two checkboxes, and a submit button has four elements, and not three (each checkbox counts as a separate element).
Secondly, if we want the chocolate vs. vanilla preference to be an either/or choice, then we should use radio buttons, and not checkboxes, for this part of the form.
Thirdly, note that for the submit button, Joe uses an onClick event handler, and not onSubmit, in the <input type="submit"> tag to pop up an alert box when submitting the form (we could use an onSubmit command but it would go in the <form> tag, as noted above).
Thursday, May 19, 2005
Event Handlers II
Blog Entry #9
(Joe outlines the procedure for internal linking in his "So, You Want A Page Jump, Huh?" tutorial. In doing this at Blogger, however, it is necessary for the target <a name="codeword"> anchor to have a closing </a> tag.
May 2016 Update: On my Intel iMac, the ice cream onFocus demo and the link onBlur demo work with Google Chrome but not with Firefox, Opera, or Safari; they worked with IE 5.1.6 back in the day but I don't know if they do or don't work with modern versions of IE.)
onClick has 'pride of place' among the event handlers, as it is the most widely applicable. Any document body element that can be (left-)clicked (even I as an old-school Mac user am using a two-button mouse these days) can hold an onClick attribute command statement in its HTML tag; for example, onClick can be used in tags for marking up text (as we saw in the last entry), links (as in the primer), images, and form elements.
In the "The onClick Command" section of the primer, a side issue crops up that is easily sorted out. Joe warns against the use of apostrophes in the alert( ) method parameter, which are "seen by the browser as the end of the text...Error." Curiously, Joe does not provide a link to his tutorial on escape characters allowing single and double quotes to appear in alert box messages. By using the backslash operator (\, appearing just above the return/enter key), we can type out the following code for a "You're off!" alert message:
<span style="color:blue;text-decoration:underline" onclick="window.alert('You\'re off!');">Click Here</span>
Try it out: Click Here
The coding for this is:
Which flavor of ice cream do you prefer?<br>
<input type="radio" name="ice_cream" onfocus="document.getElementById('van').style.background='oldlace';">
<span id="van"> Vanilla</span><br>
<input type="radio" name="ice_cream" onfocus="document.getElementById('choc').style.background='sandybrown';">
<span id="choc"> Chocolate</span><br>
<input type="radio" name="ice_cream" onfocus="document.getElementById('straw').style.background='hotpink';">
<span id="straw"> Strawberry</span>
In selecting the choices above by clicking them, you may be wondering, "Can't we just use onClick here, in place of onFocus?" Indeed we could, actually - in most cases involving form elements, the onFocus and onClick event handlers can be used interchangeably. The not-so-important difference between onFocus and onClick in this case is that we could, if we wanted to, bring focus to the "Chocolate" and "Strawberry" radio buttons without clicking them, that is, we can initially click the "Vanilla" button and then access the "Chocolate" and "Strawberry" buttons by using the tab key, but who would do that, really?
The onFocus event handler should not be paired with a window.alert( ) command; as DevGuru explains on its onFocus page, "Be aware that assigning an alert box to an object's onFocus event handler with [sic] result in recurrent alerts [i.e., the alert box will pop up over and over again, indefinitely] as pressing the 'o.k.' button in the alert box will return focus to the calling element or object." (In trying it out, I found this to be true when using Netscape but not MSIE, FWIW.)
With respect to user actions, "blur" is sort of the opposite of "focus" in that a blur event occurs when focus is removed from an element. Like onFocus, the onBlur event handler is largely applicable to form elements. The primer suggests that when onBlur is used with either a text box or a textarea box, a change in the box "value" (the text appearing in the box) is required to execute an onBlur command, although this is not true; merely clicking outside of the box with focus, changed value or not, will do it.
I'll demonstrate the onBlur event handler with a simplified version of DevGuru's example. Click inside of the text box below, and then outside of it:
The code for this is:
Enter your email address, please: <input type="text" size="40" onblur="window.alert('Please check that your email details are correct before submitting.');">
The code for this is:
<input type="text"> <a href="#" onfocus="document.getElementById('main').style.background='peachpuff';" onblur="document.getElementById('main').style.background='lemonchiffon';">This is a link.</a> <input type="text">
On my computer, the link's focus, like that of the text boxes, is indicated by a surrounding colored (MSIE, with the color being set by the Browser Color command under the View menu) or gray and tinily dotted (Netscape) rectangle. Note that a link with focus is not the same as an "active" link - a link that is 'in transit' from the "source" anchor to the "target" anchor - whose color can be set, at least for the time being, by the now-deprecated alink attribute of the document <body> tag.
Related to the onFocus and onBlur event handlers are the focus( ) and blur( ) methods, which are methods of the window object and of all of the form element objects and can be used to bring and remove focus to and from these objects. The focus( ) method will crop up in a form field validation script in Primer #29, near the end of the primer series.
Whereas onFocus and onBlur are usually used with form elements, the onChange event handler, to the best of my knowledge, is used exclusively with form elements. Of the commonly encountered form elements, the text, textarea, and select elements are those that can hold an onChange attribute in their HTML tags. For a text or textarea box, an onChange attribute command will execute upon changing the contents of the box, whether initially empty or not, and then clicking outside the box, as demonstrated in the primer for a text box. For a select element ("pop-up box"), any change in the currently selected option will execute an onChange attribute command. Try it out with the example below:
You get the idea. ;-) The code for this is:
Which flavor of ice cream do you prefer?<br>
<select onchange="window.alert('It\'s time for an ice cream cone, wouldn\'t you say?');">
<option>Mint Chocolate Chip</option>
onChange is also an event handler for the file upload form element, to which onClick, onFocus, and onBlur also all apply. File upload elements are used by some Webmail services to attach files to emails (e.g., Excite, with whom I have an email account, uses them). As an aside, DevGuru shows some requirements for sending files to others via <input type="file"> elements here.
And onChange will work with the password form element, too, or at least it does on my computer. Type a fictitious password into the box below, and then click outside of the box:
The code for this is:
Enter your password, please: <input type="password" onchange="window.alert('Are you sure that your password is typed correctly?');">
The <input type="password"> tag can similarly hold onClick, onFocus, and onBlur attribute commands.
One would think that onChange might be usable with radio button and checkbox form elements. I experimented with this a bit, and I was able to achieve a semblance of interactivity, but the overall results were not very satisfying, except for one specific case: I found that I could use onChange with checkboxes reliably when using Netscape. If you're a Netscape user, try out the following demo on your system and see if it works:
What kind of pet do you have at home? (<em>Check all that apply.</em>)<br>
<input type="checkbox" onchange="window.alert('Meow!');"> Cat<br>
<input type="checkbox"> Dog<br>
<input type="checkbox"> Bird<br>
<input type="checkbox"> Snake<br>
(If it doesn't work, well, c'est la vie.)
BTW, dynamic style changes do not constitute change events. An attempt to apply onChange to a span element with the following code was unsuccessful:
<span onmouseover="style.background='yellow';" onchange="window.alert('The background is now yellow');">The rain in Spain falls mainly on the plain.</span>
I'll continue with the other event handlers of Primer #5 - onSelect, onSubmit, onLoad, and onUnload - in my next post.
Tuesday, May 10, 2005
Blog Entry #8
Roll your mouse over the colors of the color series below:
Red Orange Yellow Green Blue Indigo Violet
(Those of you who are 'scientifically inclined' will recognize that these colors in the form of light approximately make up the visible region of the electromagnetic spectrum, which ranges from lowest energy (longest wavelength) red light through the intermediate colors of the series to highest energy (shortest wavelength) violet light. Acronym fans, remember: ROY G BIV.)
To 'statically' set a background color for a document element, we would put the attribute:
style = "background-color: colorinfo"
("colorinfo" is the desired color as a word description or hex code)
or, more simply:
style = "background: colorinfo"
into the relevant HTML tag, e.g., <p>, <span>, <div>, etc. (At HTML Goodies, discussion of the <span> tag appears here, whereas the <div> tag crops up in the "So, You Want Positioning, Huh?" tutorial.)
For example, <span style = "background-color: lightseagreen">The Pacific Ocean</span> gives: The Pacific Ocean
onmouseover = "this.style.backgroundColor = 'colorinfo';"
or, more simply:
onmouseover = "style.background = 'colorinfo';"
In these statements, "style" is simultaneously serving as (a) an object, with a backgroundColor (background) property whose value is to be 'colorinfo', and (b) a property of the "this" element.
So, getting back to the demo at the top of the page, the code for dynamically changing the background (and 'foreground') color of "Red" is:
<span onmouseover="style.background='red'; style.color='white';">Red</span>
Not so tough, eh?
The getElementById( ) method
What is the capital of Nicaragua?
(A) San Salvador
(D) San José
(again, the "Color" of "backgroundColor" can be dropped)
I trust that you can write out the complete code for all of this.
Blogger background colors, revisited
This blog makes use of the (old-school, no-longer-available) "Bluebird" Blogger template.
Click here to view the source code of my template. Click here to hide the code.
In the template, a post is contained in a <$BlogItemBody$> template tag that sits in a division element whose <div> tag holds a class="Post" attribute; in turn, the <div class="Post"> division is part of a larger division element whose <div> tag holds an id="main" attribute. To set a new background color - say, violet - for the <div id="main"> division, we can straightforwardly write:
<span onclick="document.getElementById('main').style.background='violet';">Click on this sentence to change the post background color.</span>
Try it below:
Click on this sentence to change the post background color.
Similarly, the "About Me" section of the blog that occupies the upper-right-hand corner constitutes a division whose <div> tag holds an id="menu" attribute. To set a new background color - say, gold - for the <div id="menu"> division, we could write:
<span onclick="document.getElementById('menu').style.background='gold';">Click on this sentence to change the background color of the "About Me" section.</span>
Try it below:
Click on this sentence to change the background color of the "About Me" section.
Let's get back now to the document.bgColor command, which I discussed but did not demonstrate in my last blog entry. The background color of the document is set by the body selector that kicks off the inline style block at the top of the template source; as you can see, the body's background-color property has the value "#C3CFE5", corresponding to a pale blue, which colors the stripes running up and down the sides of the template. In trying to change the color of the background side stripes, the problem here is that the document.bgColor command will not override the body selector information. What to do? The solution, it turns out, is quite simple:
(1) Remove "background-color:#C3CFE5" from the body selector; in its stead, insert a bgcolor="#C3CFE5" attribute in the <body> tag.
(2) NOW use a document.bgColor command where desired to change the document background color. To change the side stripes to red, for example, we could write:
<span onmouseover="document.bgColor='red';">Move your mouse over this sentence to change the side-stripe color.</span>
Try it below:
Move your mouse over this sentence to change the side-stripe color.
Alternatively, we could insert an id attribute - say, id="sidestripes" - in the <body> tag and then use an onmouseover="document.getElementById('sidestripes').style.background='red';" command statement in the <span> tag.
Tuesday, May 03, 2005
Event Handlers I
Blog Entry #7
(May 2016 Update: Browser support for the status property of the window object has pretty much collapsed, so don't be too heartbroken if the Primer #4 script doesn't work for you.)
Onward, now, to the onMouseOver event handler and the Primer #4 script that utilizes it:
onMouseOver="window.status='Go to the Goodies Home Page';
return true">Click Here</A>
(The above code does not need to be put on one line; it works fine just as it is.)
The command that is 'assigned' to the event handler, and which will execute in response to the mouseover event, is:
window.status='Go to the Goodies Home Page';
In this command, "window" is a host object representing the browser window; "status", in turn, refers not so much to the status bar at the bottom of the window as it does to the information (text, a URL, etc.) appearing in the status bar - the status information is classified as a property of the window object. The syntax here can be generalized as:
object.property = "value to be assigned to the property"
which is both similar to and different than the object.method( ) syntax that was introduced in Primer #1. Formally, then, our onMouseOver command will assign the 'Go to the Goodies Home Page' text string to the status property of the window object; in practice, 'Go to the Goodies Home Page' will be written to the status bar when the mouse is moved over the "Click Here" link.
Q & A
Q: Can the onMouseOver event handler be used with other HTML tags besides an <a> (anchor) tag?
A: Most certainly - pretty much any tag for an element in the body of a document can hold the onMouseOver attribute.
Mouseover examples with span, img, and button elements
(i) Move your mouse over the red words to change their color and background color.
(ii) Move your mouse over Mr. Alligator to make him grow.
(iii) Now, roll it over the button below for an important message. (We'll cover alert( ) boxes here.)
Q: Must the onMouseOver capitalization pattern be followed?
Q: What is this "return true" business, and is it necessary?
Second question: is "return true" necessary? Not really, IMHO. Using MSIE, I found that "return true" has no effect at all; I took it out and the window.status command still 'locked' the 'Go to the Goodies Home Page' text string in the status bar, i.e., subsequent mouseovers did not replace 'Go to the Goodies Home Page' with the link URL. Using Netscape, however, "return true" was indeed necessary to lock in the string; without "return true", I saw the mouseover behavior described in the primer - initially the link URL displays in the status bar, then the window.status command executes when the mouse is moved off the link, with subsequent mouseovers showing the link URL again. It's a bit counterintuitive in that you would expect the mouseover event to coincide timewise with the execution of the window.status command, but it's not as though the window.status command doesn't 'fire' at all. Moreover, Joe confesses that he prefers to not override the normal status bar display of the URL when moving the mouse over a link, and this is my preference as well.
It follows from the above that if the onMouseOver="window.status='whatever';" attribute/value is incorporated into another, nonanchor tag that has no default behavior to override, then "return true" will not be necessary to lock the new status bar message, although if you have more than one window.status command on a page, then each window.status command will override the other(s), with or without "return true".
Other primer issues
The bgColor property
In the "Other Properties, Other Uses" section of the primer, Joe re-presents the script with a new onMouseOver command:
As you would guess, "bgColor" is a property of the document object, and is used to set the background color of a document (more precisely, it sets the background color of the display of a document by a Web browser). Like the bgcolor attribute of the HTML <body> tag (and color-related attributes of other HTML tags, e.g., the color attribute of the <font> tag), the value of the bgColor document property can be in the form of either a word description (as in the command above) or a six-digit hexadecimal code (i.e., instead of 'pink', we could type 'ffc0cb', pink's "hex code").
In setting the document's background color by the mouseover event, there is no 'competition' between the execution of the document.bgColor command and the default display of the "http://www.htmlgoodies.com" link URL in the status bar; consequently, "return true" can be left out of the onMouseOver attribute value.
Two onMouseOver commands at once
In the "But I Want Both Effects" section of the primer, Joe sets up the simultaneous execution of two onMouseOver commands with the following code:
onMouseOver=window.status='Go to the Goodies Home Page';
return true">Click Here</A>
If you were to suspect that the format above is unnecessarily complicated, well, you would be right once again. Here's what I've found:
(1) Only one onMouseOver is necessary; it's not necessary to nest a second onMouseOver inside of the outlying onMouseOver attribute.
(2) The document.bgColor and window.status commands can be delimited with either a comma or (contra the primer) a semicolon.
(3) If you're going to include a "return true" statement, then it must be delimited from the rest of the attribute value with a semicolon (delimiting it with a comma will negate both of the preceding commands, regardless of how they're delimited).
Our streamlined code is thus:
<a href="http://www.htmlgoodies.com" onmouseover="document.bgColor='pink'; window.status='Go to the Goodies Home Page'; return true">Click Here</a>
I don't know if there's any limit to the number of commands that can be strung together in this manner, but in the absence of any 'conflict' between them, then they should all execute with a single mouseover, at least in theory.
One more point - if you were to have two separate onMouseOver attributes in the anchor tag:
<a href="http://www.htmlgoodies.com" onmouseover="document.bgColor='pink';" onmouseover="window.status='Go to the Goodies Home Page';">Click Here</a>
only the first onMouseOver command will execute; with the code above, you'd change the document background color but not the status bar message.
The end-of-primer assignment and its answer
Despite my best efforts, I have thus far been unsuccessful in manipulating my Blogger template code so as to allow me to show the execution of window.status and document.bgColor commands directly here on my blog. However, the end-of-primer assignment introduces a new command that I AM able to demonstrate: the window.alert( ) command. For example, move your mouse cursor over the sentence below:
Let's go for coffee.
<span onmouseover="window.alert(document.bgColor)">What is the page's background color?</span>
in this case, an alert box displays the value of the document bgColor property as a hex code (#ffffff, or white) upon rolling the mouse over the question below:
What is the page's background color?
The alert( ) method does not recognize HTML tags, however:
window.alert("<font color='red'>alert box message</font>")
will not give you an alert box with red text; rather, the HTML will appear on the box along with the message.