2

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>
Umbro
  • 1,984
  • 12
  • 40
  • 99
Lou
  • 23
  • 4
  • 4
    You can't. The client has no knowledge of what files are available in the `images` folder, unless you expose some kind of api endpoint that will give this information. – nbokmans Jul 09 '19 at 07:38
  • It would be pretty inefficient to get 100's of images just so it could choose one to use. You are better off typing them out or renaming them to something you can iterate over. – MomasVII Jul 09 '19 at 07:48

2 Answers2

0

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>
sodimel
  • 864
  • 2
  • 11
  • 24
  • Hey Sod, I'll try this out, I do have a some questions: 1. To add both .jpg and .png do I just add +".png"; after the jpg in your code? 2. You don't happen to know a way to batch rename all images in the folder in numerical order? I'll google later when home. The page will be strictly hosted locally so no worries, thanks for all the help. – Lou Jul 09 '19 at 12:42
  • Thanks Sod, once I'm home I'll give it a go and give you some feedback, cheers. – Lou Jul 09 '19 at 14:30
  • Alright, I've sucessfully converted all my images to jpg in numerical order, with the old code they display fine if I change it to 1.jpg, 2.jpg and so forth, I just need a last bit of help, how exactly do I change the code so it finds the images in the /images folder? I've never touched javascript so I'm walking in the dark here. Code posted below. – Lou Jul 10 '19 at 17:37
  • ` ` Also I have in total 235.jpg images – Lou Jul 10 '19 at 17:37
  • Edited my answer to add a "test" script. Do not forget to update the var I defined for my test with your values :) – sodimel Jul 11 '19 at 09:23
  • I did so and it worked perfectly, here's the result: https://imgur.com/a/1oMz5Wa Cheers dude, thanks so much for helping a non programmer, best wishes :) – Lou Jul 11 '19 at 11:27
  • Glad you are happy with your script :) **Edit:** do not forget to accept an answer to your question, so your post will not show on unanswered pages :) – sodimel Jul 11 '19 at 12:38
0

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!

Alcaeus D
  • 258
  • 3
  • 18