Text Rollovers: Putting the Effect to Work on an Entire Site - Doc JavaScript | WebReference

Text Rollovers: Putting the Effect to Work on an Entire Site - Doc JavaScript

Putting the Effect to Work on an Entire Site

If you want to apply the "color-changing link" effect to your front page, you'll do fine with the technique presented in the previous page. However, if your site consists of many pages, applying the link to each page separately would be quite a hassle. For example, you would need to edit each and every page to change the effect's active color. In this section we'll show you how to overcome this problem with client-side JavaScript programming (no server-side scripts here).

First of all, you will need to add two constant HTML definitions to each page:

<LINK REL="stylesheet" TYPE="text/css"
      HREF="rollover.css" TITLE="rolloversheet">
<SCRIPT LANGUAGE="JavaScript" SRC="rollover.js"></SCRIPT>
The <LINK> tag imports an external style sheet definition. Its TYPE attribute tells the browser that the style sheet is a CSS file, and the SRC attribute tells the browser that the name of that file is rollover.css. (It is assumed that your style sheet file is in the same directory as your HTML file. If not, you need to supply the directory path in the HREF attribute.) For now, all you need to put in the rollover.css file is the following line of text:

// this defines the color of a regular link
// add any other style definitions if you wish
A { color: blue }

The <SCRIPT> definition in the original HTML document imports an external script, which is responsible for the actual effect. First of all, copy and paste the following code into a file named rollover.js:

function rollon() {
  if (event.srcElement.tagName == "A") {
    event.srcElement.style.color = "red";
    event.srcElement.onmouseout = rolloff;
function rolloff() {
    event.srcElement.style.color = "blue";
document.onmouseover = rollon;

This script is very similar to the one introduced earlier in the column. However, there are several differences:

Since this color-changing rollover effect applies to all links using an <A> tag, you do not need to add any attribute or definition to the standard <A> tag. For your reference, we've created a page that utilitzes this technique.


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