简体   繁体   中英

How can I display images from a folder in random order with javascript?

What I want is simple, to have a new image display everytime I refresh the page, that is working right now, my problem is selecting those images, there's hundreds of them, both .png and .jpg. Typing out each image by name or even renaming them seems incredibly inneficient, how can I change my code so it gets all the images in the 'images' folder?

Code posted.

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>✌</title>
  </head>

  <body> <!-- This piece of Javascript will randomly decide an image for your homepage. -->

    <script>
      var pictures = ['images/Aging.png', 'images/Teddy.png', 'images/Socrates.png',];
      var picture = pictures[Math.floor(Math.random() * pictures.length)];
      document.write('<img src="' + picture + '"/>');
    </script>

  </body>
</html>

Say you have 100 images. The simplest action is to rename them with an id (say 1.jpg to 100.jpg), and call an image randomly with its name.

    function getRandomInt(max) { // number between 1 & max
      return ( Math.floor(Math.random() * Math.floor(max)) )+1;
    }

    let img = document.getElementById("yourImg");
    img.src = getRandomInt(100) +".jpg";

Another problem is the location of your images. The other computers can't navigate through your folders from another place on the world with internet, so you will need to host them where you host your website.

But if the website is created to be browsed locally, the problem will not arise.


Edit: You can verify if your file exists in js (with ajax call), but I think the easiest thing to do is to convert all your png files into jpg (or vice-versa). There are some cool utilities that can convert files with ease.

You can use mv and an index to rename all your *.jpg files.


Ex with .txt files:

script.sh

i=1
for name in *.txt; do
        mv $name $i.txt
        i=$((i+1))
done

Console view:

$> mkdir a
$> cd a
$> touch a.txt
$> touch b.txt
$> touch zerg.txt
$> touch heyy.txt
$> ls
a.txt  b.txt  heyy.txt  script.sh  zrg.txt
$> nano script.sh
$> chmod +x script.sh
$> ./script.sh
$> ls
1.txt  2.txt  3.txt  4.txt  script.sh

Edit2:

You have to create your url path with your subdirectory, your random name, and your extension.

Here is a bit of code to get you started :)

 <img id="test" /> <p id="text"></p> <script> // config, modify your values here :) let directory = "img/"; let nb_of_files = 100; function getRandomInt(max) { // number between 1 & max return ( Math.floor(Math.random() * Math.floor(max)) )+1; } let random_int = getRandomInt(100); let img = document.getElementById('test'); img.src = directory + random_int +".jpg"; document.getElementById('text').innerHTML = "Image choosen is "+ img.src +""; </script> 

You can use the Fisher-Yates Shuffle algorith to do this as mentioned here here :

 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } // Used like so var arr = ['images/Aging.png', 'images/Teddy.png', 'images/Socrates.png']; arr = shuffle(arr); console.log(arr); 

By this way, you can always print your array keys in same order but with different value every time. I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM