I was tasked with creating a card element that consistently flips in the same direction when clicked. The code snippet I found achieved this perfectly, but only worked on Chrome and Firefox. However, when testing it on Safari on both iOS and MacOS, I encountered a strange issue. After about 20 clicks, the card started flipping randomly back and forth, becoming unpredictable as seen in the screen recording provided.
Is this a common problem and is there a way to prevent this from happening?
let rot = 0;
function flip() {
rot++;
const flipContent = document.getElementById("flip").querySelector(".flip-content");
flipContent.style.transform = `rotateX(${rot * 0.5}turn)`;
flipContent.style.boxShadow = (rot % 2 === 0) ? `20px 20px 10px 0 rgba(0,0,0,0.4)` : `20px -20px 10px 0 rgba(0,0,0,0.4)`;
}
html, body {
display: flex;
margin: 0;
height: 100%;
width: 100%;
}
.flip-card {
width: 70vmin;
height: 70vmin;
margin: auto;
background: transparent;
perspective: 1000px;
transition: scale 0.3s;
scale: 90%;
cursor: pointer;
}
.flip-content {
width: 100%;
height: 100%;
transform-style: preserve-3d;
transition: all 0.6s ease-in-out;
box-shadow: 20px 20px 10px 0 rgba(0,0,0,0.4);
}
.front-face, .back-face {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.front-face {
background-color: blue;
}
.back-face {
background-color: red;
transform: rotateX(180deg);
}
.flip-card:hover {
scale: 100%;
}
<body>
<div id="flip" class="flip-card" onclick="flip()">
<div class="flip-content">
<div class="front-face"></div>
<div class="back-face"></div>
</div>
</div>
</body>