The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript random img on page load

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
  • #24202

    Iam desperately without success trying to get a different img to load up on each pageload/refresh:

    here is mycode.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    <html xmlns=""&gt;
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>Future Mind Training | Life Coaching</title>

    <link rel="stylesheet" type="text/css" href="css/styles.css">

    <script type="text/javascript">

    var images=new Array();

    ar i=Math.floor(Math.random()*images.length);

    function randomImage() {

    document.getElementById("random").src=Raw Images;



    <div id="wrapper"><!–included to allow for extension below main photos–>
    <div id="container">
    <div id="photo-frame">

    <img border="0" img id="random" src="Raw Images/photo1.jpg" width="800" height="544" >
    </div><!–end of photo-frame–>
    <!–navigation divs here–>
    <div id="col1">
    <h1 class="h1_welcome">welcome</h1>
    </div><!–end of col1–>

    </div><!–end of container–>
    </div><!–end of wrapper–>

    what is wrong with it. it does not work.

    Chris Coyier

    One thing I notice is that your original "src" starts with "Raw Images/", while the file paths in your JavaScript are just the image name. And.. when you set the .src in your randomImage function, you use "i", but "i" was declared outside of the function so it won’t know what that is. And.. that line should start "var" not "ar". And.. it should be " = images not Raw Images.

    But anyway, I don’t think JavaScript is the right route for this. Why rely on a client side language when that could potentially be disabled?

    Here is a really easy and "quick and dirty" way to do it with PHP: … -an-image/


    I got a random image replacement script on one of my pages, uses php,

    bear in ming I am just making the full image be squashed into the thumbnail area, I never resized to put a thumbnail in.


    I also agree that PHP is by far the best way to solve this problem. But supposing your host doesn’t provide PHP then you might want to try changing your randomImage function as follows:

    function randomImage() {
    var i = Math.floor(Math.random()*images.length);
    document.getElementById(“random”).src=”Raw Images/” + images[i];

    Here’s a quick and easy way to load a random image on pageload with Javascript:
    [url] … avascript/[/url]

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.