So I'm making a basic memory game, where I'm only trying to make two of the same ID images disappear whenever they are both clicked. However, the code below does work. Kind of.. But not entirely and I don't understand why. The problem is that sometimes only one image is hidden when both get clicked. Sometimes they all get hidden and it's an empty gameboard, other times 1, 2 or 3 single images gets left on the gameboard - what is causing this? Grateful for answers!
$(document).ready(function() {
var firstClicked;
$(".pictures").click(function() {
if (this.id == firstClicked) {
alert(firstClicked + " " + this.id); /*Just to see if both images get clicked*/
$(this).hide();
$("#" + firstClicked).hide();
firstClicked = null;
} else {
firstClicked = this.id;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1>Play game!</h1>
<div id="gameboard">
<div class="pic-row1">
<img src="programming.jpeg" alt="jQuery code" style="width:180px; height:180px;" class="pictures" id="programming">
<img src="confusedoldman.jpeg" alt="Confused old man" style="width:180px; height:180px;" class="pictures" id="confusedoldman">
<img src="santabeatdown.jpeg" alt="Santa ready to rumble" style="width:180px; height:180px;" class="pictures" id="santabeatdown">
<img src="sparkles.jpeg" alt="Sparkling lights" style="width:180px; height:180px;" class="pictures" id="sparkles">
</div>
<div class="pic-row2">
<img src="santabeatdown.jpeg" alt="Santa ready to rumble" style="width:180px; height:180px;" class="pictures" id="santabeatdown">
<img src="pizzalover.jpg" alt="Loving the pizza" style="width:180px; height:180px;" class="pictures" id="pizzalover">
<img src="fishbowling.jpg" alt="Fish jumping" style="width:180px; height:180px;" class="pictures" id="fishbowling">
<img src="monkeys.jpeg" alt="Monkeys" style="width:180px; height:180px;" class="pictures" id="monkeys">
</div>
<div class="pic-row3">
<img src="fishbowling.jpg" alt="Fish jumping" style="width:180px; height:180px;" class="pictures" id="fishbowling">
<img src="confusedoldman.jpeg" alt="Confused old man" style="width:180px; height:180px;" class="pictures" id="confusedoldman">
<img src="sparkles.jpeg" alt="Sparkling lights" style="width:180px; height:180px;" class="pictures" id="sparkles">
<img src="redpanda.jpeg" alt="A red panda" style="width:180px; height:180px;" class="pictures" id="redpanda">
</div>
<div class="pic-row4">
<img src="programming.jpeg" alt="jQuery code" style="width:180px; height:180px;" class="pictures" id="programming">
<img src="redpanda.jpeg" alt="A red panda" style="width:180px; height:180px;" class="pictures" id="redpanda">
<img src="monkeys.jpeg" alt="Monkeys" style="width:180px; height:180px;" class="pictures" id="monkeys">
<img src="pizzalover.jpg" alt="Loving the pizza" style="width:180px; height:180px;" class="pictures" id="pizzalover">
</div>
</div>
</body>