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
again thank you for your help.
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:
getElementbyClassName
is not a valid function. It should begetElementsByClassName
which returns an array-like collection of elements having that class name. So select the first value by writinggetElementsByClassName[0]
.Replace double quotes by single quotes here:
'images/' selectedImages
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;