0

I want to randomly loop all the images that is present in a folder. Currently I'm able to manually enter each image one by one and it displays. But I want the function to display images by itself from a given folder.

JS

function rndmImg() {
        var qs = [
            {
            text: "1",
            img:  "/Images/1.png"
            },
            {
            text: "2",
            img:  "/Images/2.png",
            },
            {
            text: "3",
            img:  "/Images/3.png",
            },
            {
            text: "4",
            img:  "/Images/4.png",
            },
            {
            text: "5",
            img:  "/Images/5.png",
            },
        ];
        var q = qs[Math.floor(Math.random() * qs.length)];
        document.getElementById("q").innerHTML =
            '<p>' + q.text + '</p>' +
            '<img src="' + q.img + '">';
        }

HTML

<div id="quote"></div>
        <input class="Click me" style="float: left;" type="button" 
        value="Randomize" onclick="rndmImg()">
ikol
  • 83
  • 1
  • 9
  • If your server supports a directory-index of the `Images` directory, you might be able to parse the response – Phil Sep 15 '20 at 01:11
  • 4
    So your real problem is to get your backend to list the images in a folder and a way to retrieve that list in your code. Do you have control over your backend? Is it a webserver like apache or nginx? Just listing files is often referred to as "autoindex". If you use nginx autoindex can output json directly which is very easy to retrieve from your javascript. If you are running some api backend, creating a new endpoint that lists images could be the right step. – ippi Sep 15 '20 at 01:12

1 Answers1

1

So client side JavaScript, even if running on a local server, doesn't actually have access to the local file system, so the typical server side or command line commands like readdir, cd ls etc don't actually exist in client side JavaScript

That being said, if it's running on some kind of server / static http server of some sort, you should be able to fetch the main directory with an XMLHttpRequest, or fetch, read the links and then later loop through the images etc

In fact, without running on a server of some sort in the first place, client side JavaScript can't read the bytes of any external file, unless it is chosen by the user

So if you're running a local static server on port 770 using pythons http_server module, for example, then to get the files

fetch("http://localhost:770/Images")
.then(r=>r.text())
.then(r=>{
    var p=new DOMParser ()
    var s=p.parseFromString(r,"text/html")
    var links=Array.from(s.querySelectorAll("a"))
    var fileNames= links.map(x=>x.href)
})

(Assuming there is no index.html in that directory)

That being said it would appear your files all follow a pattern of incrementing by one. If they all follow a known pattern, you don't need a server at all, you can simply dynamically create new Image objects in JavaScript, and set an onload function as well as an onerror function for each, and only add the ones with no error, or keep recursively loading them unless one of them has an error, and when it has an error, that will tell you that the pattern has been broken, and you don't need a server

So assuming the pattern is the name increments by one, starting at 1.png, then you can generate an array of objects with the name and image object itself in each element, like this

makeObjectArray (1, "Images/", ".png", it=>{
    console.log(it)
})
function makeObjectArray(cur,start,end, done) {
     var ar=[]
    get1()
    function get1() {
        var im= new Image()
        im.src=start+ (cur++)+end
        im.onload=()=> (ar.push(im),get1())
        im.onerror=()=>done (ar)
    }
}
  • Thanks for answering. I'm actually using electron to create a desktop app. I'm trying to find a way to show images located in the app folder. So I do have a index.html present in the app folder. Is there a way to loop the images in the folder in a random order? – ikol Sep 15 '20 at 01:20
  • @ikol do you have control of the server side code? – B''H Bi'ezras -- Boruch Hashem Sep 15 '20 at 01:30
  • yes, I do have control over server side code – ikol Sep 15 '20 at 01:32
  • @ikol so just make a route for the Image directory to give back a. JSON list of all the files in that directory, there should be some kind of readdir command in your server side code to return an array of files. You can then either just load it from client side js and parse it as a JSON and randomly loop through it there or simply shuffle the array on the server side,, does that work? – B''H Bi'ezras -- Boruch Hashem Sep 15 '20 at 01:35
  • I think that should work. I'm going to give it a try. Thank you so much for the clear explanation! – ikol Sep 15 '20 at 01:37