Forum Moderators: open

Message Too Old, No Replies

Changing a foreground image on load using javsascript.

         

nelsonm

7:59 am on Dec 4, 2010 (gmt 0)

10+ Year Member



Hi all,

I have an existing web page i have modified. It used to change the background image in a <td>. However, i now need it to change a foreground image in the <td>.

The javascript to generate the a new image file name is already coded. I just don't know how to modify the the <img> src= parameter to accept the javascript generated image name variable "scr".

The code follows...

<script type="application/JavaScript">

var num = Math.ceil(Math.random()*5);
var src = "images/bg-masthead" + num + '.jpg';

document.getElementById("banner-L").src = src;

</script>
</head>

<body>
<table id="wrapper2" cellpadding="0" cellspacing="0">
<tr>
<td>
<table width="100%">
<tr>
<td id="banner-R"><img id="banner-L" align="left" src="images/bg-masthead-left.jpg"></td>
</tr>
</table>
</td>
</tr>

daveVk

1:31 pm on Dec 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Code looks okay, but timing may be premature. Try moving the script block to just prior </body>

nelsonm

5:57 pm on Dec 5, 2010 (gmt 0)

10+ Year Member



thanks, but it was constantly changing the image, so i changed it to...


<script type="application/JavaScript">

function getImage() {
var num = Math.ceil(Math.random()*5);
var isrc = "images/bg-masthead-L" + num + ".jpg";

document.getElementById("banner-L").src = isrc;
}

</script>
</head>

<body onload="getImage()">
<table id="wrapper2" cellpadding="0" cellspacing="0">
<tr>
<td>
<table width="100%">
<tr>
<td id="banner-R"><img id="banner-L" align="left" src="images/bg-masthead-L1.jpg"><?php include("/inc/search.htm"); ?></td>
</tr>
</table>
</td>
</tr>

daveVk

11:18 pm on Dec 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Placing script prior to the </body> is claimed to be a more efficient alternative to onload. Interesting that it does not work in this case.

rocknbil

5:13 pm on Dec 6, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<script type="text/javascript">
window.onload=function() { getImage(); }
function getImage() {
var num = Math.ceil(Math.random()*5);
var isrc = "images/bg-masthead-L" + num + ".jpg";
document.getElementById("banner-L").src = isrc;
}
</script>
</head>
<body>