Change Background Color
The following chunk shows how to make changes to the background color of a few table elements. In this example, the action is applied only to the TD element of the table that it is declared within. You can apply this method to any page element that DOM allows access to, including making document-wide changes through altering the values of attributes of the BODY tag.
These change methods can be used in one page element or in sweeping changes you can accomplish such as through the use of CSS rules. Simply alter the DOM statement stated in the JavaScript within the script tags given in the head of the document accordingly.
<html>
<head>
<script type="text/javascript">
function bgChange(bg)
{
document.body.style.background=bg;
}
</script>
</head>
<body>
<b>Mouse over the squares and the background color will change</b>
<table width="300" height="100">
<tr>
<td onmouseover="bgChange('red')"
onmouseout="bgChange('transparent')"
bgcolor="red">
</td>
<td onmouseover="bgChange('blue')"
onmouseout="bgChange('transparent')"
bgcolor="blue">
</td>
<td onmouseover="bgChange('green')"
onmouseout="bgChange('transparent')"
bgcolor="green">
</td>
</tr>
</table>
</body>
</html>
Some things that you might want to play around with are changing which events fire the changes stated in the DOM statement, what properties are altered, and if you want to go a bit further and assign a variable loaded with information that is decided upon by other functions such as according to stored user preference.
To do this, change from using a literal value as the argument passed to the bgChange() function. For example, use a variable name instead of the word “green” – the actual color to be applied can be decided upon in another function and is contained as the data of the variable. You may use named colors, hex colors, or RGB colors as the method of defining what color is to be applied.
|