Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    May 2012
    Posts
    16
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Random Image Generator

    I need a bit of help. So on my website i want a button which a person can click, and when they click on it, a image appears from the image file (lets say around 20 images can be picked).

    Is javascript the best way to do this, and if so is there any open-source code i could use for this?

    Thanks.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,146
    Thanks
    203
    Thanked 2,547 Times in 2,525 Posts
    Quote Originally Posted by nick1o2 View Post
    I need a bit of help. So on my website i want a button which a person can click, and when they click on it, a image appears from the image file (lets say around 20 images can be picked).

    Is javascript the best way to do this, and if so is there any open-source code i could use for this?

    Thanks.
    Try this:-
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    </head>
    <body>
    
    <input type = "button" value ="Click here to obtain another image" onclick = "getImages()">
    <br><br>
    <img id = "myImage" src = "One.gif">
    
    <script type = "text/javascript">
    var imgs = ["Two.gif", "Three.gif", "Four.gif", "Five.gif"];  // as many images as you wish - no comma after final one
    
    function shuffle(array) {
    var n = array.length, k, t;
    if (n == 0) return false;
    while (--n) {
    k = Math.floor(Math.random() * (n+1));
    t = array[n];
    array[n] = array[k];
    array[k] = t;
    }
    }
    shuffle(imgs);  // shuffle the images array
    
    var count = 0;
    function getImages() {
    document.getElementById("myImage").src = imgs[count];
    count ++;
    if (count >= imgs.length) {
    shuffle(imgs);  // shuffle the array again if desired
    count = 0;
    }
    }
    
    </script>
    </body>
    </html>

    Scotland have to understand the pressure they are under, and relieve themselves ... - Commentator BBC Radio 5 Live

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

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