javascript: random image selected on refresh

24,908

Solution 1

How about:

HTML:

<img id="image" />

JS:

var description = [
  "http://static.ddmcdn.com/gif/lightning-gallery-17.jpg",
  "http://static.ddmcdn.com/gif/lightning-gallery-18.jpg",
  "http://static.ddmcdn.com/gif/lightning-gallery-19.jpg",
  "http://static.ddmcdn.com/gif/lightning-gallery-20.jpg",
  "http://static.ddmcdn.com/gif/lightning-gallery-21.jpg"
];

var size = description.length
var x = Math.floor(size*Math.random())
document.getElementById('image').src=description[x];

No jQuery necessary.

Solution 2

http://jsfiddle.net/mohammadAdil/SvswX/

<img id='random'/>

script -

var image = new Array ();
image[0] = "http://placehold.it/20";
image[1] = "http://placehold.it/30";
image[2] = "http://placehold.it/40";
image[3] = "http://placehold.it/50";
var size = image.length
var x = Math.floor(size*Math.random())

$('#random').attr('src',image[x]);
Share:
24,908
Ryan Saxe
Author by

Ryan Saxe

Updated on July 09, 2022

Comments

  • Ryan Saxe
    Ryan Saxe almost 2 years

    So I have a site in which I have a description area and I have it be a random description on refresh by using the following code:

    <script type="text/javascript">
    var description = new Array ();
    description[0] = "I can change";
    description[1] = "Isn't it cool";
    description[2] = "these are just to show you guys";
    description[3] = "another thing";
    var size = description.length
    var x = Math.floor(size*Math.random())
    document.write(description[x]);
    </script>
    

    Now my question, is if I wanted to have it display random images on refresh rather than a random description, how would I do it? I assume it will take a bit of jquery and maybe some appending, but I'm really not sure.

    Thanks!

  • nnnnnn
    nnnnnn about 11 years
    +1. Note that this would need to be in a script element that appears after the <img>, or wrapped in an onload handler.
  • Jared Michael Czerew
    Jared Michael Czerew about 9 years
    @urban_racoons - would this code work if I'm using images in the asset pipeline in Rails? IE- var description = [ "images/imageOne.jpg", etc etc
  • urban_raccoons
    urban_raccoons about 9 years
    @JaredMichaelCzerew yeah as long as <img src="images/imageOne.jpg"> would evaluate correctly. If this code is inside a rails template, there's likely a (better?) way to do this using the rails framework itself.