0

I'm very new to HTML and want to create my own website. On my website I want a button that when pressed returns a random image stored on the server. This image needs to be displayed on the same page. From several sources i found code that looks like this:

function pickimg(){
    var imagenumber = 5 ;
    var randomnumber = Math.random() ;
    var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
    images = new Array
    images[1] = "IMAGE #1"
    images[2] = "IMAGE #2"
    images[3] = "IMAGE #3"
    images[4] = "IMAGE #4"
    images[5] = "IMAGE #5"
    var image = images[rand1]
    document.randimg.src = image
}

The problem with this approach is that the list of files needs to be determined beforehand. The list of different pictures is very long and it seems inefficient to make a separate entry for each file. My javaScript skills are non-existent but i do know some python.

This code wil add every filename in my folder to a list just like the JavaSCript Example, although it's now automated.

pictlist = []
path = "website\\pictures"
files = os.listdir(path)
for picture in files:
    pictlist.append(picture)

My question is then, How can i translate this python code into JavaScript and what HTML code do i need to add to the tag?

Thanks!

Aydin4ik
  • 1,782
  • 1
  • 14
  • 19
  • Possible duplicate of [JavaScript Display Random Images](https://stackoverflow.com/questions/19693256/javascript-display-random-images) – lscmaro Aug 14 '17 at 01:02
  • Are the files really named `IMAGE #1` with no extension? What are the names of the files and what web server are you using? Maybe rename the photos to something like `99.jpg`, `100.jpg`, `101.jpg` etc. – styfle Aug 14 '17 at 01:06
  • no the files have all kinds of names, this was just an example. This example however is not what I exactly want from the code. I have hunderds of files and don't want to add them manually to the JavaScript code. – yannick van niel Aug 14 '17 at 01:24
  • Please correct me if I am wrong. Javascript, due to security reason, strongly prohibit manipulation of one's directory/files. If you go to any websites with JS behind and if JS is similar to python/C#/etc , all your documents could be stolen by sites' host. Therefore, I am afraid there is no equivalent JS code to your python code. You need to hardcode image source. – tim1234 Aug 14 '17 at 01:40
  • Are you in Node environment? If so you can do it, see [here](https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j). If you are in browser environment, you can still use your python code by making javascript requesting random image from server, and server (which is written by python) sends back the name of random image – paibamboo Aug 14 '17 at 01:45

0 Answers0