reptile7's JavaScript blog
Tuesday, May 03, 2005
 
Event Handlers I
Blog Entry #7

One of the most useful aspects of JavaScript is that the execution of JavaScript commands can be triggered by various user actions, e.g., loading a Web page, clicking a link, moving the mouse, etc., which are in JavaScript collectively termed "events". JavaScript links a user action with a resulting command via a part of speech called an event handler, to which we turn our attention in both HTMLGoodies' JavaScript Primers #4 and #5. Primer #4 focuses on a single event handler, the onMouseOver event handler, which, as its name implies, executes a command when the mouse cursor is moved over a document element; Primer #5 will introduce eight further event handlers for our delectation. Parenthetically, there is in JavaScript an event object, which is created automatically on the occurrence of an event and which is recognized by later versions of MSIE and Netscape; the event object doesn't crop up anywhere in the HTMLGoodies JavaScript primers but does appear late in the script tip series, in the "Cat Chases Your Mouse" script of Script Tip #91.

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

<A HREF="http://www.htmlgoodies.com"
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.)

You may be thinking to yourself, "This isn't a script at all...this onMouseOver thing is really just an attribute in an HTML tag", and you would be right, more or less - that's pretty much how event handlers function. (Event handlers can be put in JavaScript scripts, but the coding to do this is more complicated than that shown above, and it's just not necessary most of the time.)

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?

A: No. Capitalization is not important for event handlers; to the best of my knowledge, this is the one situation to which JavaScript's case-sensitivity does not apply. "onMouseOver", "onMouseover", and "onmouseover" are all acceptable (even oNmOuSeoVEr will work, I can confirm).

Q: What is this "return true" business, and is it necessary?

A: In JavaScript, the word "return" is classified as a statement; it is typically used inside of a function (a 'packet' of ≥1 statements - we'll get to JavaScript functions in Primer #9) to return a value to the point on the page that 'calls' (triggers) the function. Here, "return" is serving an analogous purpose by returning to the onMouseOver event handler the boolean value "true", which guarantees that, yes, the window.status='Go to the Goodies Home Page' command statement will well and truly execute regardless of anything that might preempt it; specifically in this case, "return true" causes the window.status command to override the 'default HTML behavior' of displaying the "http://www.htmlgoodies.com" URL in the status bar that would ordinarily occur when the mouse moves over the link.

Joe's attempted explanation of "return true" in the primer - "[i]f the words are present, then the script checks to see if a status bar is present" - is really rather bizarre; clearly, the presence or absence of the status bar merely determines whether or not you'll see the 'Go to the Goodies Home Page' text string, and not whether the window.status command executes in the first place. But in fairness to Joe, neither DevGuru nor JavaScript Kit is helpful on this topic. The best account I've seen on the Web on the use of "return true" in setting the status property of the window object via the onMouseOver event handler appears in <Code_Punk>'s JavaScript Lesson 13, to which my discussion above is indebted.

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:

onMouseOver="document.bgColor='pink';"

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.

bgColor is also a property of the JavaScript layer object. Layers are specifically supported by the Netscape 4.x browser series (Netscape 6+ doesn't recognize them) and are thus not much use to us, but they do crop up in the script tips, and we can talk about them then.

Finally, you may know that the use of cascading style sheets (CSS) allows background coloring to be applied not just to the entire page but to various elements of a document. CSS-based background coloring can be dynamically set with JavaScript; the coding to do this is a bit more advanced than that shown in the Primer #4 script, but at the risk of getting somewhat ahead of ourselves, I may well flesh this out in my next blog entry.

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:

<A HREF="http://www.htmlgoodies.com"
onMouseOver="document.bgColor='pink',
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.

As noted on the HTMLGoodies JavaScript methods keyword reference page but not in the primer, alert( ) is a method of the window object; as shown by my demo, it generates a box with (a) a message, which is supplied by the alert( ) parameter, and also (b) an OK button. In the example above and also in the primer assignment, the alert box displays a text string; it can also be used to display the values of object properties and variables. Consider the following code:

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

You'll note in the primer assignment that the alert( ) method does not need to reference the window object, i.e., the "window." part has been left out - this is 'allowed', if a bit sloppy, because the window object is at the top of JavaScript's 'host object hierarchy', which we'll get to in Primer #8, and thus its "existence is assumed". Relatedly, the window.status = "message" command statement can also simply be written as status = "message".


I think that's quite enough for Primer #4, don't you? Before we get stuck into Primer #5, I have some more things to say about JavaScript and background coloring, and I'll do that in the next entry.

reptile7

Comments: Post a Comment

<< Home

Powered by Blogger

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