PDA

View Full Version : Random image problem



wax0nightmare
09-14-2008, 10:54 AM
http://www.dynamicdrive.com/forums/archive/index.php/t-17207.html

Hi there,

I've been using this piece of javascript to load an image randomly from an array:


window.onload = function() {
var randomImages = [
"img/logo1.gif",
"img/logo2.gif",
"img/logo3.gif",
];
document.images['random_image'].src = randomImages[Math.floor(Math.random() * randomImages.length)];
};

I have the script linked to an HTML file, and an id is linked on an img tag like this:


<img id="random_image" src="img/logo1.gif" width="700" height="252" border="0" />

and it works fine for the topmost level of my site, but when i try link the same script into an HTML file that is down one level in a folder, the randomizer does not work. I figured out that each image has to go up one level to find an image and then bring it in, like this:



window.onload = function() {
var randomImages = [
"../img/logo1.gif",
"../img/logo2.gif",
"../img/logo3.gif",
];
document.images['random_image'].src = randomImages[Math.floor(Math.random() * randomImages.length)];
};

If I were two levels down it would be:


"../../img/logo1.gif",

and so on. This means I have to have three separate javascript files. Does anyone know of a way to just have the one, but target all images?

Thanks guys :D

jscheuer1
09-14-2008, 01:27 PM
Use the absolute (network actually in this example) path to the images:


window.onload = function() {
var randomImages = [
"/img/logo1.gif",
"/img/logo2.gif",
"/img/logo3.gif",
];
document.images['random_image'].src = randomImages[Math.floor(Math.random() * randomImages.length)];
};

If the script already worked in the root of the domain, the above would be good for the entire domain. If you need more help:

Please post a link to the page on your site that contains the problematic code so we can check it out.