Home > Back-end >  Multiple div Flip in same page
Multiple div Flip in same page

Time:07-26

How can I tweak the below codes to make it possible for multiple divs to do this flip on the same page ?

J.s works for only the first entry But I want to be able to flip multiple divs on same page.

var card = document.querySelector('.card');
card.addEventListener('click', function() {
  card.classList.toggle('is-flipped');
});
.flip-box {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
}

.card {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 1s;
  transform-style: preserve-3d;
}

.flip-box-front,
.flip-box-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-box-front {
  background-color: #bbb;
  color: black;
}

.flip-box-back {
  background-color: #333;
  color: white;
  transform: rotateY(180deg);
}

.card.is-flipped {
  transform: rotateY(180deg);
}
<div >
  <div >
    <div >
      <h2>Front Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>
    <div >
      <h2>Back Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>
  </div>
</div>

CodePudding user response:

First, I changed querySelector to querySelectorAll. Then, I loop through all the cards on the page and attach the click event handler, exactly as you had initially.

var cards = document.querySelectorAll('.card');

cards.forEach(card => {
  card.addEventListener('click', function() {
    card.classList.toggle('is-flipped');
  });
})
.flip-box {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
}

.card {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 1s;
  transform-style: preserve-3d;
}

.flip-box-front,
.flip-box-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-box-front {
  background-color: #bbb;
  color: black;
}

.flip-box-back {
  background-color: #333;
  color: white;
  transform: rotateY(180deg);
}

.card.is-flipped {
  transform: rotateY(180deg);
}
<div >
  <div >
    <div >
      <h2>Front Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>

    <div >
      <h2>Back Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>

    </div>
  </div>

  <div >
    <div >
      <h2>Front Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>

    <div >
      <h2>Back Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>

    </div>
  </div>
</div>

  • Related