PDA

View Full Version : Why can't this javascript code run ?


chu2654
11-17-2005, 02:49 AM
I want when the user points to a picture link, the picture will become another one. But the following code will always have erros: document[...] is null or is not an object. What's the problem ?

<script language="JavaScript" type="text/javascript">
<!--
productoff = new Image;
productoff.src = "./img/product.gif";
productover = new Image;
productover.src = "./img/news.gif";


function replaceImg(oldImg,newImg){
document[oldImg].src = eval(newImg + ".src");
}
//-->

</script>


<td><a href="./product.html" onMouseOver = "replaceImg('productoff','productover')" onMouseOut = "replaceImg('productoff','productover')" ><img src = "./img/product.gif" ></a></td>

Horus_Kol
11-17-2005, 03:21 AM
you need to tell the function what object on the page is being modified - in this case, the <img> tag... the <img> tag needs an id attribute so you can identify in the javascript...

to do something similar on one site of mine, i did this:


function opt_hover(img_no)
{
var img = document.getElementById("nav_idx_img_opt" + img_no);
img.src = opt_image;

var a = document.getElementById("nav_idx_a_opt" + img_no);
a.style.color = "#FFFF00";
}

function opt_clear(img_no)
{
var img = document.getElementById("nav_idx_img_opt" + img_no);
img.src = "img/transp.gif";

var a = document.getElementById("nav_idx_a_opt" + img_no);
a.style.color = "#FFFFFF";
}




<a class='nav_idx_a_opt' href='introduction.php'><img id='nav_idx_img_opt1' class='nav_idx_img_opt' src='img/transp.gif' alt='Introduction' onmouseover='opt_hover(1)' onmouseout='opt_clear(1)' /></a>