I need to load a different image after, lets say 10 seconds.
So image1.gif will be displayed when the page loads then after say 10 seconds image2.png will replace image1.gif.
How would go about doing this.
Thanks.
03-01-2011, 10:24 AM
WolfShade
Simple enough in JavaSCRIPT, don't know about Java.
Basically, as long as every element in the web document has a unique ID, you can manipulate or read just about anything for that element, including the source. And JavaScript has a "setTimeout" function that can do the "every 10 seconds" part.
So, let's use the following arbitrary code as an example:
HTML Code:
<img id="img1" src="/images/image1.gif" />
Inside the HEAD tags at the top, you can do something like:
Code:
function swapImage() {
var thisImg = document.getElementById('img1');
thisImg.src = "/images/image2.png";
setTimeout("swapImage()",10000);
}
window.onload = swapImage;
Now.. this will only change the source to image2.png, and will reset to image2.png every ten seconds. But you can create an array of image names and use those referencing the array index and setting a variable to increment by one with each iteration; stipulate that once the variable gets to the max length of the array, reset to zero.
^_^
03-01-2011, 10:47 AM
tobyhutton1234
Thanks for this, however the browser (IE 8) returns an error:
'null' is null or not an object
Line: 3, Char: 3
Code:
function swapImage() {
var thisImg = document.getElementById('img1');
thisImg.src = "/images/image2.png";
setTimeout("swapImage()",10000);
}
window.onload = swapImage;
I assume its the line highlighted in red.
03-01-2011, 10:51 AM
WolfShade
The image element is named 'img1'?
I suppose it could be a timing issue; if the image isn't loaded at onload, this could account for the null issue.
Also, just for giggles, give the image the same name as the id.
^_^
03-01-2011, 12:02 PM
clueful
This swaps after 5 seconds but can be changed. Just replace your own image names in the img tag and the function call:
Code:
<img src = 'original.jpg' id = 'myImage'>
<script type="text/javascript">
/*<![CDATA[*/
function loadAfter( imgId, delay, newImage )
{
var holder = document.getElementById( imgId ),
buffer = new Image();