phantom phantom - 1 month ago 20
Javascript Question

CSS Flip animation on click

I am following the example David Walsh provides to make a flip animation. Its is all working on hover, however, I want to flip the element on click as opposed to on hover.

The following code works and flips the element on hover, however, I want to use javascript/jquery to implement this. I have tried many different ways but cannot figure out how to do this.



.flip-container {
perspective: 1000px;
}
.flip-container:hover .flipper,
.flip-container.hover .flipper {
transform: rotateY(180deg);
}
.flip-container,
.front,
.back {
width: 320px;
height: 480px;
}
.flipper {
transition: 0.6s;
transform-style: preserve-3d;
position: relative;
}
.front,
.back {
backface-visibility: hidden;
position: absolute;
top: 0;
left: 0;
}
.front {
z-index: 2;
transform: rotateY(0deg);
}
.back {
transform: rotateY(180deg);
}

<div class="flip-container" ontouchstart="this.classList.toggle('hover');">
<div class="flipper">
<div class="front">
1
</div>
<div class="back">
2
</div>
</div>
</div>




Answer

https://jsfiddle.net/pf4aemn7/ HTML

<div class="flip-container" ontouchstart="this.classList.toggle('hover');">
  <div class="flipper">
    <div class="front">
      1
    </div>
    <div class="back">
      2
    </div>
  </div>
</div>

CSS

.flip-container {
  perspective: 1000px;
}

.flip-container.hover .flipper {
  transform: rotateY(180deg);
}
.flip-container,
.front,
.back {
  width: 320px;
  height: 480px;
}
.flipper {
  transition: 0.6s;
  transform-style: preserve-3d;
  position: relative;
}
.front,
.back {
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
}
.front {
  z-index: 2;
  transform: rotateY(0deg);
}
.back {
  transform: rotateY(180deg);
}

JS

$(document).on("click", ".flip-container", function () {
    $(this).toggleClass('hover');
});