SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jun 2007
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Random images on refresh

    I'm hoping someone can help... this random script doesn't always show the images when the page is refreshed... usually only one image will show, and the others come up with red x's. I don't understand what's wrong.

    Here's the code:

    Code:
    <script language="javascript">
    <!--
    
    // add image URLs, separated by commas
    var images = new Array('http://tinyurl.com/28s8x4', 'http://tinyurl.com/28kv9c', 'http://tinyurl.com/yocw49');
    
    document.write('<img src = "' + images[Math.floor(Math.random()*images.length+1)] + '"border = "0" alt = "Cats rule!" />');
    
    //-->
    </script>
    and here's a link to it on practicewriter:

    http://practicewriter.com/vu/?1971D


    Thanks, any help would be really appreciated.

  2. #2
    SitePoint Evangelist hexburner's Avatar
    Join Date
    Jan 2007
    Location
    Belgium
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you look at an array, the index always starts with 0, so the array images looks like:
    images[0] = 'http://tinyurl.com/28s8x4';
    images[1] = 'http://tinyurl.com/28kv9c';
    images[2] = 'http://tinyurl.com/yocw49';

    Then take a look at this images[Math.floor(Math.random()*images.length+1)]
    Let's break it down:
    images.length = 3
    So Math.random() * 3+1 would translate in a number between 0 and 4.
    BUT the maximum index of the array is 2, so you have index 3 and 4 that are empty.
    You need Math.random() * 3-1...

    The solution: images[Math.floor(Math.random()*images.length-1)]
    FOR SALE: 1 set of morals, never used, will sell cheap

  3. #3
    SitePoint Member
    Join Date
    Jun 2007
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for your reply and explanation. I'd forgotten about the arrays starting at 0. It has trouble with the 3rd image.

    I tried the change but still couldn't get it to work, so I guess I'm still confused.

    Thank you.


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
  •