Text Rollovers: Changing a Link's Color - Doc JavaScript | WebReference

Text Rollovers: Changing a Link's Color - Doc JavaScript

Changing a Link's Color

With Internet Explorer 4.0 it's very easy to dynamically modify an element's style after the page has been displayed. Each element's style is referenced in JavaScript using the style property. Suppose the variable element reflects an HTML element. The following statement sets its color to "black":

element.style.color = 'black';

In the same fashion, you can modify any one of an element's style attributes by assigning a value to one of the properties of the style property. The following code segment shows how to create a simple link that changes its color when the user passes the mouse over it:

<A HREF="http://www.microsoft.com/">
<FONT COLOR="#0000ff"
      onMouseOver="this.style.color = '#cc0000'"
      onMouseOut="this.style.color = '#0000ff'">Microsoft</FONT></A>

* Notice that we split the code into several lines to make it easier to read. You should always put the entire code on one line.

If you're using Internet Explorer 4.0, here's the interactive link in action: Microsoft. If you are not using Explorer 4.0, this will appear to be a plain link -- nothing special.

The this object in the event handler scripts refers to its HTML element (the <FONT>...</FONT> definition). We use this "shortcut" instead of using the full object path for the element. The reason why we use the <FONT> tag instead of placing the event handlers directly in the <A> tag, is that we want to make sure the event handler script executes only if the user is running Internet Explorer 4.0. Any other JavaScript-enabled browser supports onMouseOver and onMouseOut in a plain link, so they would execute the event handler script and generate a JavaScript error when encountering the reference to the object's style property (this is a unique IE 4.0 property). Another reason to use the <FONT> tag is that it is relatively easy to control colors with its COLOR attribute as well as with its color style definition.


Created: October 9, 1997
Revised: December 4, 1997
URL: http://www.webreference.com/js/column4/color.html