Home > Software engineering >  How to get one random HTML file from one folder and add it to an iframe?
How to get one random HTML file from one folder and add it to an iframe?

Time:09-05

I have a folder called myfolder with several files. I would like to select only the HTML files of this folder, and put them randomly into an iframe.

So this is my idea:

// Get HTML files

var pages = ["myfolder/1.html", "myfolder/2.html", "myfolder/3.html"]; // Instead of this, all HTML files of the folder 'myfolder/' should be selected


// Get one random HTML file of selection and add it to the iframe

$(".random-page").attr("src", "myfolder/"   pages[Math.floor(Math.random() * pages.length)]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<iframe ></iframe>

What can be written instead of var pages = ["myfolder/1.html", "myfolder/2.html", "myfolder/3.html"]; to select all HTML files from one folder? And does it work then with the code that I wrote?

CodePudding user response:

If you know there will be exactly 10 files, named 1.html, 2.html, etc., there is no need for your pages array:

$(".random-page").attr('src', 'myfolder/'   ( Math.floor(Math.random() * 10)   1 )   '.html');
  • Related