0

I made a basic one page html website and styled it. I have a small image gallery (6 images) and I want to use JS to display these images in a different order every time the page is refreshed. If the page isn't refreshed, I want it to be on a timer to refresh the images.

I know I would have to use Math.random, and I could use onload with an interval timer to change the images. I've done some research and I can't figure out how to implement this. Could anyone point me in the right direction?

Here's the html portion of the image gallery:

<section id="gallery">
    <img src="./images/1.jpg" alt="img0">
    <img src="./images/2.jpg" alt="img1">
    <img src="./images/3.jpg" alt="img2">
    <img src="./images/4.jpg" alt="img3">
    <img src="./images/5.jpg" alt="img4">
    <img src="./images/6.jpg" alt="img5">
</section>
97x
  • 7
  • 5

5 Answers5

1

Here's an example.

const getRandomNumber = (function() {
    var nums = [1,2,3,4,5,6];
    var current = [];
    function rand(n) {
        return (Math.random() * n)|0;
    }
    return function() {
      if (!current.length) current = nums.slice();
      return current.splice(rand(current.length), 1);
    }
}());

const images = document.querySelectorAll('#gallery img');

getRandomImages = () => {
  const imagesNums = [];
  for (let i = 1; i < 7; i++) {
    imagesNums.push(getRandomNumber());
  }

  images.forEach((img, index) => {
      img.src = `./images/${imagesNums[index]}.jpg`
  })
}

setInterval(() => {
   getRandomImages()
}, 10000);
<section id="gallery">
    <img src="./images/1.jpg" alt="img0">
    <img src="./images/2.jpg" alt="img1">
    <img src="./images/3.jpg" alt="img2">
    <img src="./images/4.jpg" alt="img3">
    <img src="./images/5.jpg" alt="img4">
    <img src="./images/6.jpg" alt="img5">
</section>
onlit
  • 728
  • 5
  • 19
  • Thanks [RobG](https://stackoverflow.com/users/257182/robg) for the random function – onlit Nov 20 '20 at 18:09
  • Thanks! So now I understand how the randomize on page refresh is working, and the images refreshing once after the interval, but how would I continue to refresh these images every x seconds? Right now it only seems to refresh once after the timer. – 97x Nov 20 '20 at 18:24
  • I'm passing `10000` milliseconds to `setInterval`. which are equal to 10 seconds. you can tweak the value if you want – onlit Nov 20 '20 at 18:32
  • Thank you, this is perfect! One last question though, if you don't mind. I was reading about the onload Event. How could I use the onload event to change the images every few seconds instead of using setInterval? I would like to learn it for future reference. – 97x Nov 20 '20 at 18:38
  • The load event fires when a script has loaded it has nothing to do with timer. but you can use it to verify if script is loaded before running the code. you can learn more about it [here](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload) – onlit Nov 20 '20 at 18:39
0

Keep all the image sources in an array.

const imgSources = ['./images/1.jpg', './images/2.jpg', './images/3.jpg'];

Select a random item from your list

const randomItem = Math.floor(Math.random())

Then select the image from the html and set the source attribute

const image = document.querySelector('#gallery'); // Assuming you have only 1, replace with id

image.setAttribute('src', randomItem); 

We have done the part for a random image. Now its similar with a setInterval

setInterval(() => {
   const randItem = Math.floor(Math.random() * arr.length);
   image.setAttribute('src', randItem); 
}, 3000); // 3s

Thats it! I'd recommend making a function for a random no and then setting the attribute in both places so you don't repeat yourself

You can make a function like this -

function changeImage(img) {
   const randItem = Math.floor(Math.random() * arr.length);
   img.setAttribute('src', randItem); 
} 

This function can be called inside the setInterval and in the start of the code. Remember to pass in the image!

Cheers

Akash
  • 762
  • 7
  • 25
  • Thank you for the response. I can't seem to get this working, not sure what I am doing wrong. Would I change the id to the id of my image gallery which is 'gallery' ? Would you please give me an example of the last part about the function? – 97x Nov 20 '20 at 18:29
0
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>

    <body>
        <img id="image" src="./images/1.jpg">

        <script type = "text/javascript">
            var image = document.getElementById("image");
            var currentPos = 0;
            var images = ["./images/2.jpg", "./images/3.jpg", 
                           "./images/4.jpg","./images/5.jpg,./images/6.jpg]

            function auto_pic() {
                if (++currentPos >= images.length)
                    currentPos = 0;

                image.src = images[currentPos];
            }

            setInterval(auto_pic, 4000);
        </script>
    </body>
</html>`
Tanmay Brv
  • 89
  • 4
0

Just replace Onclick event with Window Refresh Event

HTML

<div id="box">
<img id="image" />
</div>
<br />
<input type="button" value="Randomize!" onClick="randImg()" />

Javascript

    var images = [
    "https://png.pngtree.com/thumb_back/fh260/background/20190222/ourmid/pngtree-blue-atmospheric-background-image_50584.jpg",
    "https://radioralitafm.com/wp-content/uploads/2018/01/Blue-Background-Images-HD-Wallpapers-Backgrounds-of-Your-....jpg",
    "https://sinargarudaprima.files.wordpress.com/2013/08/blue-abstract-vista-wallpaper00000.jpg",
    "https://i.pinimg.com/originals/09/43/75/094375b4af674b559ac8a00a8c8d6662.jpg"];

function randImg() {
    var size = images.length
    var x = Math.floor(size * Math.random())
    document.getElementById('image').src = images[x];
}
randImg();

Here Demo JSFIDDLE

Adhitya
  • 660
  • 1
  • 4
  • 18
0

Here is how I would do it (given your HTML above):

  1. Start with your "gallery" section empty. Just put the section there with no images.
  2. Create a function that writes the content (image tags) of your "gallery" section.
  3. Call that function on page load.
  4. Set a timer to either run your function on a schedule, or to refresh the page after a certain amount of time.

I was hesitant to give the complete code for what looks like it could be a homework assignment, but I see several other full answers. So here is what this looks like:

<body onload="drawImages()">
<section id="gallery">
</section>

<script>
    function drawImages() {
        let myImage = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"];
        shuffle(myImage);

        // You'll have to play with this to get the alt text as you 
        //   specified, if that is important.
        let imageHTML = "";
        for (let i = 0; i < myImage.length; i++) {
            imageHTML += '<img src="./images/' + myImage[i] + '" alt="' + myImage[i] + '">';
        }

        document.getElementById('gallery').innerHTML = imageHTML;
    }

    function shuffle(array) {
        // Try your shuffle function first. If you can't get it working,
        //   copy the complete working function from the accepted answer 
        //   at:
        // https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
    }

    setInterval(function(){drawImages();}, 2000);
</script>
</body>

Good luck.

HumanJHawkins
  • 240
  • 2
  • 9
  • I'm pretty confused. I was trying to figure this out last night, but got stuck on a few parts. Would you be able to show me how to do the parts that you explained as comments? I figured out the shuffle function, but after that I get a little lost. I appreciate the response. – 97x Nov 21 '20 at 16:44
  • I notice one of my comments was really confusing, and I had an error. I've corrected this and tested it using the shuffle function I reference. You might try it with your own shuffle function first. But the one referenced can be dropped in to make this work if needed. – HumanJHawkins Nov 23 '20 at 02:46