Home > Enterprise >  random images change with every refresh made
random images change with every refresh made

Time:12-15

so I have linked two images in HTML from the folder: images/ however in javascript I'm trying to make these images for the dice to randomly change after every time refreshes. I'm not sure why isn't working

here is the HTML code

<div >
  <h1>Refresh Me</h1>

  <div >
    <p>Player 1</p>
    <img  src="images/dice6.png">
  </div>

  <div >
    <p>Player 2</p>
    <img  src="images/dice6.png">
  </div>

    </div>

and here is the js code

imgArray = [
"dice1.png",
"dice2.png",
"dice3.png",
"dice4.png",
"dice5.png",
"dice6.png"
]


function images(){
  // the random images
  var randomNumber1 = Math.floor(Math.random() * imgArray.length);
  // get images at randomNumber1
  selectedImages = imgArray[randomNumber1]
  // display the images()
  document.getElementByClassName("img1").src = "./images/${selectedImages}"

}

Note: I'm a new learner still trying to understand javascript. thank you for your humble reply and help. and if isn't too much to make the explanation simple so I could follow.

after fixing the code above


function images(){
  // the random images
  var randomNumber1 = Math.floor(Math.random() * imgArray.length);
  // get images at randomNumber1
  selectedImages = imgArray[randomNumber1]
  // display the images()
  document.getElementsByClassName("img1")[0].src = './images/${selectedImages}'
}

window.onload = images;

I have problem when I refresh the page this is what it does show

enter image description here

again thank you for your help.

here what it show

okay fixed, here I did change it with

function images(){
  // the random images
  var randomNumber1 = Math.floor(Math.random() * imgArray.length);
  // get images at randomNumber1
  selectedImages = imgArray[randomNumber1]
  // display the images()
  document.getElementsByClassName("img1")[0].src = 'images/'   selectedImages;
  document.getElementsByClassName("img2")[0].src = 'images/'   selectedImages;
}

window.onload = images;

CodePudding user response:

There are few issues here:

  1. getElementbyClassName is not a valid function. It should be getElementsByClassName which returns an array-like collection of elements having that class name. So select the first value by writing getElementsByClassName[0].

  2. Replace double quotes by single quotes here: 'images/' selectedImages

  3. Don't forget to call the function when the windows is loaded.

Final Code:

function images(){
  // the random images
  var randomNumber1 = Math.floor(Math.random() * imgArray.length);
  // get images at randomNumber1
  selectedImages = imgArray[randomNumber1]
  // display the images()
  document.getElementsByClassName("img1")[0].src = 'images/'   selectedImages;
}

window.onload = images;
  • Related