Results 1 to 2 of 2

Thread: Random image problem

  1. #1
    Join Date
    Sep 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Random image problem

    http://www.dynamicdrive.com/forums/a...p/t-17207.html

    Hi there,

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

    Code:
    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:

    Code:
    <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:


    Code:
    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:

    Code:
    "../../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
    Last edited by wax0nightmare; 09-14-2008 at 11:13 AM.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Use the absolute (network actually in this example) path to the images:

    Code:
    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.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •