February 18, 2000 - Changing a Link's Text | WebReference

February 18, 2000 - Changing a Link's Text

Yehuda Shiran February 18, 2000
Changing A Link's Text
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Modifying HTML code dynamically (after the page has loaded) is fairly simple with Internet Explorer. You need to address the desired HTML element, and assign the new code to its innerHTML property. Use innerText if you only want to print plain text, with no tags. The following code segment creates a link that dynamically changes when the user passes the mouse pointer over it:

<A HREF="http://www.microsoft.com/">
<FONT onMouseOver="this.innerHTML = 'The Software Tycoon'"
      onMouseOut="this.innerHTML = 'Microsoft'">Microsoft</FONT></A>

The result of the preceding definition is this link: Microsoft. It acts as a normal link in Navigator 4.0x, and in any other browser that does not support the above features. Notice how Explorer automatically reformats the paragraph due to the additional text ("The Software Tycoon" is longer than "Microsoft"). If your link is not surrounded by text (and images), the browser won't need to perform this reformatting, which might initially seem annoying.

Be aware that the alternative text ("The Software Tycoon" in our example) should be longer than the default text. If it's shorter, and the user placed the mouse over the right-hand side of the link, the onMouseOver handler would fire, and the new text would appear. But since the new text is shorter than the original one, the link is obviously shorter, so the mouse pointer is no longer located over the link. Therefore, an onMouseOut event handler is immediately fired, and so forth. The result would be a very distracting, flashing link. Here's an example:

Microsoft If you're running Internet Explorer 4.0, pass the pointer over the left-hand side of the link. It should work fine. Now pass it over the right-hand side, and you'll notice the problem.

Learn more about text rollover in Column 4, Text Rollover.