Background Image Swap - TD

The images used for the background should be the same size as the td cell, each TD cell used is given an ID

Example 1

The mouse events are applied to the td cell, this means that when the mouse enters the td cell the background changes.
If the td cell or contents within the cell are clicked the background will change.

For this effect put onmouseover="mOver(this)" onmouseout="mOut(this)" onclick="mActive(this)" in the opening TD cells tag

Example 2

The mouse events are applied to the link so the background only changes when you mouseover, mouseout, or click the link

For this effect put onmouseover="mOver(this.offsetParent)" onmouseout="mOut(this.offsetParent)" onclick="mActive(this.offsetParent)" in the links opening tag

You can have a td cells active image showing when the page loads by placing onload="mActive('td_id')", where td_id is the appropriate cell ID, in the opening body tag.

The following code is set for example 2

<HTML>
<HEAD>
<TITLE>TD Background Image Swap</TITLE>

<script type="text/javascript">

var images = new Array("bgout.jpg","bgover.jpg","bgactive.jpg")

var preloadImages=new Array() // preloads images
for(var i=0;i<images.length;i++) {
preloadImages[i]=new Image()
preloadImages[i].src=images[i]
}

lastN = ""

function mOver(obj){
if(lastN != obj.id){
document.getElementById(obj.id).style.backgroundImage ="url("+images[1]+")"
}
}

function mOut(obj){
if(lastN != obj.id){
document.getElementById(obj.id).style.backgroundImage = "url("+images[0]+")"
}
}

function mActive(obj){
id=(typeof obj=="object"?obj.id:obj)

document.getElementById(id).style.backgroundImage = "url("+images[2]+")"
if (lastN != "" && lastN != id){
document.getElementById(lastN).style.backgroundImage = "url("+images[0]+")"
}
lastN = id
}

</script> 

<style>

#menutable td{
width:120px;
height:30px;
text-align:center;
background-image:url(bgout.jpg);
}

</style>

</HEAD>
<BODY onload="mActive('td1')">
<h1>TD Background Image Swap</h1>

<center>
<table id="menutable" border="0">
<tr>
<td id="td1"><a href="page1.htm" onmouseover="mOver(this.offsetParent)" onmouseout="mOut(this.offsetParent)" onclick="mActive(this.offsetParent)">Link 1</a></td>
<td id="td2"><a href="page2.htm" onmouseover="mOver(this.offsetParent)" onmouseout="mOut(this.offsetParent)" onclick="mActive(this.offsetParent)">Link 2</a></td>
<td id="td3"><a href="page3.htm" onmouseover="mOver(this.offsetParent)" onmouseout="mOut(this.offsetParent)" onclick="mActive(this.offsetParent)">Link 3</a></td>
<td id="td4"><a href="page4.htm" onmouseover="mOver(this.offsetParent)" onmouseout="mOut(this.offsetParent)" onclick="mActive(this.offsetParent)">Link 4</a></td>
</tr>
</table>
</center>

</BODY>
</HTML>