Home > Net >  Click event only works once in querySelectorAll - javascript
Click event only works once in querySelectorAll - javascript

Time:10-25

I am currently trying to make a board game in the style of memory (I am self taught, and things like that help me great in understanding javascript). My question is probably basic stuff, but I am new to all of this so I appreciate any help.

My problem is that I have two cards with the same class, and with my code, when I click on first or second one, it only works on the first card.

document.querySelectorAll(".first-card").forEach(container => {
  container.addEventListener('click', flipCard)
})

function flipCard() {
  document.querySelector(".first-card").classList.toggle("flip")

}
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  padding: 100px;
  display: flex;
}

.first-card,
.second-card {
  width: 100px;
  height: 150px;
  border: 3px solid black;
  border-radius: 10px;
  transition: 0.6s;
  transform-style: preserve-3d;
  position: relative;
  margin: 10px;
}

.flip {
  transform: rotateY(180deg);
}

.front,
.back {
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
}

.front {
  z-index: 2;
  transform: rotateY(0deg);
}

.back {
  transform: rotateY(180deg);
}

.first-card .front {
  background: lightblue;
  width: 100%;
  height: 100%;
}

.second-card .front {
  background: red;
  width: 100%;
  height: 100%;
}

.first-card .back,
.second-card .back {
  background: black;
  width: 100%;
  height: 100%;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <link rel="stylesheet" type="text/CSS" href="memory.css" />
</head>

<body>
  <div >
    <div >
      front
    </div>
    <div >
      back
    </div>
  </div>

  <div >
    <div >
      front
    </div>
    <div >
      back
    </div>
  </div>

  <div >
    <div >
      front
    </div>
    <div >
      back
    </div>
  </div>

  <div >
    <div >
      front
    </div>
    <div >
      back
    </div>
  </div>

  <script src="memory.js"></script>
</body>

</html>

Like I said, I am only beginner, so any help or explanation is welcome. Thank you

CodePudding user response:

It "doesn't work" because in your flipCard function you're getting the first element that matches with the className fist-card. This element will be always the same one. Just change your function to this:

function flipCard(v){
    v.currentTarget.classList.toggle("flip")
}

CodePudding user response:

use below

function flipCard(event){
    event.target.classList.toggle("flip")  
}

evt.currentTarget, which would refer to the parent in this context. So it would not be handy for you I believe. see mdn for it

  • Related