Entry
How can I set the background image of a table cell?
How can I set the background color of a table cell?
May 26th, 2001 01:46
Martin Honnen,
With NN4 you need to make your table cell, the TD element, a layer to
be able to script it. Then you can script
document.cellID.background.src = 'whatever.gif';
IE4+ simply allows you to script the
background
property of the TD element.
But in the time of CSS it is better to use
elementReference.style.backgroundImage = 'url(whatever.gif)';
The following code that works with NN4, NN6, and IE4+ allows to change
the background color and the background image of a table cell:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
table cell background color and background image change
</title>
<style type="text/css">
.cell { position: relative; }
body { background-color: orange; }
</style>
<script type="text/javascript">
function setBgColor (id, color) {
if (document.layers)
document[id].bgColor = color == 'transparent' ? null : color;
else if (document.all)
document.all[id].style.backgroundColor = color;
else if (document.getElementById)
document.getElementById(id).style.backgroundColor = color;
}
function setBackgroundImage (id, imageURL) {
if (document.layers)
document[id].background.src = imageURL == 'none' ? null : imageURL;
else if (document.all)
document.all[id].style.backgroundImage = imageURL == 'none' ? 'none'
: 'url(' + imageURL + ')';
else if (document.getElementById)
document.getElementById(id).style.backgroundImage = imageURL ==
'none' ? 'none' : 'url(' + imageURL + ')';
}
</script>
</head>
<body>
<a href="javascript: void 0"
onclick="setBgColor ('aCell', 'lime');
return false;"
>
lime
</a>
|
<a href="javascript: void 0"
onclick="setBgColor ('aCell', 'transparent');
return false;"
>
no background color
</a>
|
<a href="javascript: void 0"
onclick="setBackgroundImage ('aCell', 'kiboInside.gif');
return false;"
>
kiboInside.gif
</a>
|
<a href="javascript: void 0"
onclick="setBackgroundImage ('aCell', 'none');
return false;"
>
no background image
</a>
<table border="1">
<tr>
<td id="aCell" class="cell">
Kibology for all.
<br />
All for Kibology
</td>
</table>
</body>
</html>