reptile7's JavaScript blog
Thursday, May 19, 2005
 
Event Handlers II
Blog Entry #9

After the detour of the last episode, we return to the HTML Goodies JavaScript primers, specifically, to Primer #5 in continuance of our discussion of event handlers that we began two entries ago. With onMouseOver now under our belt, we will in today's entry briefly look at Primer #5's first four event handlers:

onClick
onFocus
onBlur
onChange

(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

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

onFocus

When you 'select' a form element (e.g., a text box, textarea box, radio button, checkbox, etc.), either by clicking it or by moving to it via a tab operation, you bring "focus" to that element, and this focusing event can trigger the execution of a JavaScript command via the onFocus event handler. For example, consider the ice cream-related question below, and see what happens when you select the various flavors:

Which flavor of ice cream do you prefer?
Vanilla
Chocolate
Strawberry

The coding for this is:

<form>
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>
</form>

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.)

onBlur

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:

Enter your email address, please:

The code for this is:

<form>
Enter your email address, please: <input type="text" size="40" onblur="window.alert('Please check that your email details are correct before submitting.');">
</form>

Less intuitively, focus and blur events can also apply to links. In illustration, click on the left text box below, and then press the tab key to access the central link, and then press the tab key again to access the right text box:

This is a link.

The code for this is:

<form>
<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">
</form>

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.

Lastly and more practically, focus can be brought to and removed from the browser window (the windows of Internet pop-under ads are "blurred", for example). The focusing or blurring of windows can execute JavaScript code by the use of onFocus and onBlur command statements, respectively, in the <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.

onChange

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:

Which flavor of ice cream do you prefer?

You get the idea. ;-) The code for this is:

<form>
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>Butter Pecan</option>
<option>Cherry Vanilla</option>
<option>Mint Chocolate Chip</option>
<option>Rocky Road</option>
</select>
</form>

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:

Enter your password, please:

The code for this is:

<form>
Enter your password, please: <input type="password" onchange="window.alert('Are you sure that your password is typed correctly?');">
</form>

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:

<form>
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>
</form>

(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.

reptile7

Comments: Post a Comment

<< Home

Powered by Blogger

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