DragonHeart000
DragonHeart000

Reputation: 1096

How To Get Random Number In HTML/Java Script And Have Something Different Happen With Each One

I am trying to make a HTML file that will open a random picture out of 6. What I have already will only open the one the one that I specify. Is there a way to make it open a random one.

    <!DOCTYPE html>
        <body>
            <img src="IMG_1643.jpg" width="100%"/>
            <script type="text/javascript">
                setInterval("window.close()", 10000);
            </script>
        </body>

The names of the 6 images I have are:

^04CA0231DA52E6C51B485BD9D7B46A52692ECC1CCB4F6E30A4^pimgpsh_fullsize_distr.jpg
^EE8BDA9E7F039326CF7340D2B4849A4ECA9E466F65BF7C4EE3^pimgpsh_fullsize_distr.jpg
IMG_1643.jpg
YTpic1 .png
YTpic2.jpg
YTpic2.gif

Upvotes: 1

Views: 296

Answers (1)

xsami
xsami

Reputation: 1330

This is what you need: JSfiddle - change img on reload.

In this example I'm using images from the internet but what you should do is to change the elements names on the array and everything will work fine. Example: change this "http://images4.fanpop.com/image/photos/22200000/-ZORO-one-piece-22288454-414-479.jpg" for this "YTpic2.gif".

This is the HTML code:

<img src="d" id="myImg"/>

This is the JavaScript code:

var images = [ "http://images4.fanpop.com/image/photos/22200000/-ZORO-one-piece-22288454-414-479.jpg", "http://3.bp.blogspot.com/-VOiVpheXW_g/UmkqgPZFMZI/AAAAAAAAASU/0BF1y4ox4Bw/s1600/nico_robin_2y_by_deiviscc-d3jdk02.png", "http://www.renders-graphiques.fr/image/upload/normal/Zoro_calendrier_2013_by_Kakarot.png", "http://img2.wikia.nocookie.net/__cb20120302234410/onepiece/es/images/archive/9/90/20130106193654!Timeskip_Zoro.png", "http://st-listas.20minutos.es/images/2013-07/364756/4091397_640px.jpg?1373467101", "http://i615.photobucket.com/albums/tt232/Celtanor/Manga%20and%20Anime%20Renders/One%20Piece/RoronoaZoro17B.png"
];

(function () {
    document.getElementById("myImg").src = images[Math.ceil(Math.random() * images.length)-1];
})()

Upvotes: 1

Related Questions