So I am trying to flip a card when it is being clicked. I did a console.log(card[i]) just before addEventListener and it works fine but error appeared on the console.log after that addEventListener.
The error I got is: Uncaught TypeError: Cannot read property 'style' of undefined
These are my code
var card = document.querySelectorAll('.card');
var cardInner = document.querySelectorAll('.card-inner');
var cardBack = document.querySelectorAll('.card-back');
for (var i=0; i < card.length; i++) {
console.log(card[i]); // works fine
// when a card is clicked
card[i].addEventListener('click', function(){
// flip THAT card
console.log(card[i]); // undefined value
card[i].style.perspective = "500px";
cardInner[i].style.transform = "rotateY(180deg)";
cardInner[i].style.transition = "all 0.5s";
cardBack[i].style.transform = "rotateY(180deg)";
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Memory Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section class="box">
<div class="card">
<div class="card-inner">
<div class="card-front"></div>
<div class="card-back"></div>
</div>
</div>
<div class="card">
<div class="card-inner">
<div class="card-front"></div>
<div class="card-back"></div>
</div>
</div>
</section>
<script src="app.js"></script>
</body>
</html>