mardi 15 octobre 2019

Display a row of random pictures in browser from an array using javascript

I want to display 6 pictures in a row. Eventually I want to click the picture and have it display full screen like IMDB. First though I need to display the 6 pictures randomly from an array of 48 image urls. The images are being stored on S3.

I've tried different methods but none have worked so far. First I used getElementById but on my html <img> tag, it is not using the id part and is using the src part and displaying the static link. My tag looked like this:

<img src="https://accountName.s3.us-east-2.amazonaws.com/assets/avengers_5.jpg" id="avengerPic">

The browser is showing the avengers_5 pic and not the one generated by my function in the id="avengerPic". The reason I have the avengers_5.jpg listed is because I don't know what else to put there. The resource I used to learn how to do this had this as the src: images/spacer.gif. When I take the src off and leave just the id, it displays nothing.

This is my array (abridged):

let picArray = [
  "https://accountName.s3.us-east- 
  2.amazonaws.com/assets/avengers_1.jpg",
  "https://accountName.s3.us-east- 
  2.amazonaws.com/assets/avengers_2.jpg",
  "https://accountName.s3.us-east- 
  2.amazonaws.com/assets/avengers_3.jpg",
  "https://accountName.s3.us-east- 
  2.amazonaws.com/assets/avengers_4.jpg"
]

(Remember, there are really 48 pics)

This is my function:

let moviePics = function() {
  let randomPic = Math.floor(Math.random() * picArray.length);
  document.getElementById("avengerPic").src = picArray[randomPic];
}

This is my html:

<table>
 <tr>
  <img src="https://accountName.s3.us-east- 
  2.amazonaws.com/assets/avengers_5.jpg" id="avengerPic">
  <img src="https://accountName.s3.us-east- 
  2.amazonaws.com/assets/avengers_5.jpg" id="avengerPic">
 </tr>
</table>

The result I want is to have 6 random images from my array displayed horizontally. I've been able to do it statically in a table and formatted with CSS. Now I just want to change it from static images, to random images from my array of 48 image url's. Lastly, I will make it so when you click an image it opens up full screen with arrows that allow you to click left or right through all 48 images.




Aucun commentaire:

Enregistrer un commentaire