I am building a flashcard game where the user would select the animal group, then a random animal from that group would pop up on screen.
However, the same value appears regardless of what value is passed to the function displayAnimal(datavalue)
Here is the troublesome part:
var classname = document.getElementsByClassName("row")
for (var i = 0; i < classname.length; i++) {
var datavalue;
datavalue = classname[i].getAttribute("data-animal-cat");
classname[i].addEventListener("click", function() {
displayAnimal(datavalue);
});
}
Here is the full code:
var birdArray = ["Owl", "Hummingbird", "Toucan"]
var dogArray = ["Bulldog", "Dash Hound", "German Shepard"]
var fishArray = ["Goldfish", "Mahi Mahi", "Catfish"]
var randomBird = birdArray[Math.floor(Math.random() * birdArray.length)];
var randomDog = dogArray[Math.floor(Math.random() * dogArray.length)];
var randomFish = fishArray[Math.floor(Math.random() * fishArray.length)];
function initFlashCardGame() {
var classname = document.getElementsByClassName("row")
for (var i = 0; i < classname.length; i++) {
var datavalue;
datavalue = classname[i].getAttribute("data-animal-cat");
classname[i].addEventListener("click", function() {
displayAnimal(datavalue);
});
}
function displayAnimal(datavalue) {
var animalType;
if (datavalue === "birds") {
alert(randomBird);
} else if (datavalue = "dogs") {
alert(randomDog);
} else if (datavalue = "fish") {
alert(randomFish);
}
}
}
//add event listener when window loads
window.addEventListener("load", initFlashCardGame);
#container {
width: 100%;
max-width: 480px;
margin: auto;
font-family: arial;
border: 2px solid black;
padding: 10px;
}
.row {
background: #116995;
pading: 20px;
margin: 6px;
padding: 20px;
font-size: 20px;
color: white;
}
.row:hover {
background: yellow;
color: red;
font-weight: bold;
font-size: 25px;
}
p {
display: block;
text-align: center;
color: black;
font-size: 25px;
font-weight: bold;
}
<div id="container">
<p>SELECT ANIMAL GROUP</p>
<div class="row" data-animal-cat="birds">
Birds
</div>
<div class="row" data-animal-cat="birds">
Dogs
</div>
<div class="row" data-animal-cat="birds">
Fish
</div>
</div>