If you're looking to control the flipping animation by changing a class, here's a suggestion. Start by setting up your card's normal styles in your CSS and then add transform: rotateY(180deg)
when the extra class is applied.
This approach allows you to add the class when a card is clicked and remove it after a set timeout. By including a transform transition (e.g., transition: transform 500ms
) on your card, you'll experience smooth transitions as the card flips both ways.
You can toggle this class using the click function and a predefined timeout in your script.
Below is an example of how you can dynamically add and remove classes using vanilla JavaScript along with a timeout function. Take note of how we add a flipped
class to #wrapper
using JavaScript for the desired animation effect.
Keep in mind that this solution utilizes element.classList
, which is compatible with Internet Explorer 10 and above. If you need to support versions earlier than IE 10, explore options mentioned in this thread.
document.getElementById('wrapper').addEventListener('click', function() {
var wrapper = this;
wrapper.classList.add('flipped');
setTimeout(function() {
wrapper.classList.remove('flipped');
}, 1500);
});
#wrapper {
perspective: 1000px;
width: 100px;
height: 150px;
}
#wrapper.flipped .card {
transform: rotateY(180deg);
}
.card {
width: 100%;
height: 100%;
position: relative;
transition: transform 500ms;
transform-style: preserve-3d;
}
.card .front,
.card .back {
width: 100%;
height: 100%;
border-radius: 15px;
position: absolute;
top: 0;
left: 0;
backface-visibility: hidden;
}
.card .front {
background-color: midnightblue;
z-index: 1;
}
.card .back {
background-color: firebrick;
transform: rotateY(180deg);
}
<div id="wrapper" style="float: left;">
<div class="card">
<div class="front"></div>
<div class="back"></div>
</div>
</div>
<p style="float: left; margin: 65px 0 0 10px;">← click me</p>