Problem with Javascript Card Flip

Asked

Viewed 48 times

-2

1 answer

2

Use the querySelectorAll() to haggle all occurrences of .card and then on those occurrences with the forEach(), example:

var cards = document.querySelectorAll('.card'); // Pegar todas ocorrências
cards.forEach((card) => { // Iterar sobre elas adicionando o listener
  card.addEventListener( 'click', function() {
    card.classList.toggle('is-flipped');
  });
})
body { font-family: sans-serif; }

.scene {
  width: 200px;
  height: 260px;
  border: 1px solid #CCC;
  margin: 40px 0;
  perspective: 600px;
}

.card {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
  transform-style: preserve-3d;
  transform-origin: center right;
  transition: transform 1s;
}

.card.is-flipped {
  transform: translateX(-100%) rotateY(-180deg);
}

.card__face {
  position: absolute;
  width: 100%;
  height: 100%;
  line-height: 260px;
  color: white;
  text-align: center;
  font-weight: bold;
  font-size: 40px;
  backface-visibility: hidden;
}

.card__face--front {
  background: red;
}

.card__face--back {
  background: blue;
  transform: rotateY(180deg);
}
<div class="scene scene--card">
  <div class="card">
    <div class="card__face card__face--front">front</div>
    <div class="card__face card__face--back">back</div>
  </div>
  <div class="card">
    <div class="card__face card__face--front">front</div>
    <div class="card__face card__face--back">back</div>
  </div>
</div>
<p>Click card to flip.</p>

  • Thank you very much! It worked super well. But why did people deny my question? I’m new here, what’s wrong with doubt? Thanks!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.