Foreground Colors

This page is obsolete and retained for archival purposes only.
Please refer to: Changing the color of HTML elements and Applying CSS Stylesheets.

Question: How do I change the text and link colors of the document?

Answer: You might have been told that it's impossible to change the foreground colors (that is, text and link colors) because the JavaScript properties document.fgColor, document.linkColor and the like are read-only, and you cannot set these properties. That means, the colors defined in the BODY tag of your page will remain unchanged no matter what you try to set; all you can do is change the background.

Well, that's right... almost right... but try this:

It works like this: the script saves the new color settings, then reloads the page, reads the saved settings and document.write's the BODY tag with the new colors. What? Saves?, you might say, Can JavaScript really save files???

The trick is simple: the script can save the new color settings not in a file, but in a variable of another window or frame. And even if there might be no other windows/frames available, then the script still can use a cookie.

The script on this page actually uses both techniques, a cookie and a variable in the top-level frameset. Thus, this script would fail to reset the text and link colors only if the user disabled cookies and the page is loaded in a top-level window of the browser. If you would like to reuse this code, just cut-and-paste it from the source of this page. Enjoy!

Just one final note: in Internet Explorer 4, the properties document.fgColor, document.linkColor, document.vlinkColor, document.alinkColor are no longer read-only. You can set these properties to change colors!

Copyright © 1999-2011, JavaScripter.net.