Changing Stylesheet Attributes

Question: I am trying to get the following script to work.

<style type="text/css">
body {background-color:#cccccc; }
<a href="#" onmouseover="document.bgColor='#ffff00';">yellow</a>
<a href="#" onmouseover="document.bgColor='#00ff00';">green</a>

The background colour will only change if I have no background colour set via CSS. I want the background for the entire page to change based on which hyperlink the mouse is placed over. I do not want to use tables.

Answer: The problem is that the stylesheet background colour completely overrides any background colour defined on the body tag. This means that any background colour assigned via the bgcolor= on the body statement will be ignored. The document.bgColor reference updates the colour assigned to bgcolor= on the body tag but this is still overridden by the stylesheet and so the changed value is still ignored.

To change the background colour when you have one defined in a stylesheet you need to change the stylesheet colour and not the one assigned via the body tag. The easiest way to do this is to define separate classes for the body and assign them different background colours (any other attributes only need to go on the first body tag unless you want them to change as well). Then all you need to do is to change the class assigned to the body in order to change the colour. You will need to assign an id to the body tag so that you can reference it. The code looks like this:

<style type="text/css">
body {background-color:#cccccc;}
.yellow {background-color:#ffff00;}
.green {background-color:#00ff00;}

<body id="bdy">
<a href="#" onmouseover="bdy.className='yellow';">yellow</a>
<a href="#" onmouseover="bdy.className='green';">green</a>

You can change the background colour of parts of your document other than the entire body of the document by specifying the id of the part of the document that you want to change in place of the id from the body tag. The same also works for changing any other attributes that can be defined using stylesheets.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow