I'm not fully understanding 'this', I have checked another answer to the same question, but as the base code was quite different I found I was getting lost. I couldn't figure out what I should be binding meanwhile some of the other answers didn't use 'this' or binding at all.
I am trying to do something very simple, add and remove a class from a single element when clicked, but I want to apply this to multiple elements with only the one clicked triggering each time.
I would like to understand and do this in JS, not jQuery. Which would be an easy short cut but leave me just as baffled.
const flipCard = document.querySelectorAll(".card--holder");
const card = document.getElementById("card");
flipCard.forEach(card => {
card.addEventListener("click", flipCards);
})
const flipCards = () => {
if (card.classList.contains("flipped")) {
this.classList.remove("flipped");
} else {
this.classList.add("flipped");
}
}
.flip {
-webkit-perspective: 800;
width: 400px;
height: 200px;
position: relative;
margin: 50px auto;
}
.flip .card.flipped {
-webkit-transform: rotateY(-180deg);
}
.flip .card {
width: 100%;
height: 100%;
-webkit-transform-style: preserve-3d;
-webkit-transition: 0.5s;
}
.flip .card .face {
width: 100%;
height: 100%;
position: absolute;
-webkit-backface-visibility: hidden;
z-index: 2;
text-align: center;
line-height: 200px;
}
.flip .card .front {
position: absolute;
z-index: 1;
background: black;
color: white;
cursor: pointer;
}
.flip .card .back {
-webkit-transform: rotateY(180deg);
background: blue;
color: black;
cursor: pointer;
}
<div class="card--holder flip">
<div class="card" id="card">
<div class="face front">Front</div>
<div class="face back">Back</div>
</div>
</div>
<div class="card--holder flip">
<div class="card" id="card">
<div class="face front">Front</div>
<div class="face back">Back</div>
</div>
</div>
<div class="card--holder flip">
<div class="card" id="card">
<div class="face front">Front</div>
<div class="face back">Back</div>
</div>
</div>