I've got an array of images which display on button click in random order. I've confirmed that all images are clickable and that they display the correct image source in the console. What I am unable to do is create a on click event that alerts a message when an image is clicked. When I click image "A1", alert "No" is displayed, so I'm guessing that the problem may be that the image string and the actual image aren't linked together?
const images$front = [
{ name: "A1", img: "A1.png" },
{ name: "B1", img: "B1.png", },
{ name: "A2", img: "A2.png", },
{ name: "B2", img: "B2.png", },
{ name: "A3", img: "A3.png", },
{ name: "B3", img: "B3.png", },
{ name: "A4", img: "A4.png", },
{ name: "B4", img: "B4.png", },
];
//Rear image
const images$rear=[
{ name: "z", img: "z.png" , },
];
function shuffle(array) {
let currentIndex = array.length,
randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]
];
}
}
shuffle(images$front)
function DisplayImage(i) {
let CardImage = document.createElement('img');
CardImage.src = `Images/${images$front[i].img}`
CardImage.alt = CardImage.src;
document.querySelector("#box").appendChild(CardImage);
CardImage.addEventListener("click", function(e) {
if (CardImage === "A1") {
alert("Yes")
} else {
alert("No")
}
console.log(e.target.src)
})
}
Thanks
Your condition is trying to equal between the object to string, CardImage is HTMLImageElement, that always will be false , you can add another property "name" and then make the condition.
function DisplayImage(i) {
let CardImage = document.createElement('img');
CardImage.src = `Images/${images$front[i].img}`
CardImage.alt = CardImage.src;
CardImage.name = images$front[i].name; //here is the change.
document.querySelector("#box").appendChild(CardImage);
CardImage.addEventListener("click", function(e) {
if (CardImage.name === "A1") { //change here too.
alert("Yes")
} else {
alert("No")
}
console.log(e.target.src)
})
}