I'm trying to get a random election of an image in javascript, and it works, but when I click a button and the image changes, randomElement still being the same as the first time it worked. I'm trying to update it using the same name for another random election, but isn't working. Here is the code:
document.addEventListener('DOMContentLoaded', function() {
const catbutton=document.getElementById('catbutton')
const cubebutton=document.getElementById('cubebutton')
const image=document.getElementById('image')
var x=0
var arr= ["pr1.jpg", "pr2.jpg"]
const randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement)
image.src=(randomElement);
catbutton.onclick=function() {catfunction()};
function catfunction(){
if (randomElement=="pr1.jpg"){
x++;
alert(x)
const randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement)
image.src=(randomElement);
}
else if (randomElement=="pr2.jpg"){
alert("Fallaste!")
}
}
cubebutton.onclick=function() {cubefunction()};
function cubefunction(){
if (randomElement=="pr2.jpg"){
x++;
alert(x)
const randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement)
image.src=(randomElement);
}
else if (randomElement=="pr1.jpg"){
alert("Fallaste!")
}
}
})
Aucun commentaire:
Enregistrer un commentaire