Technologies:
Tolerim
a day ago
What is the method for rotating an element in JavaScript to achieve a flip card effect?
const game = document.querySelector(".game");
const nums = [];
var generateNumber = () => {
for (i = 1; i <= 16; i++) {
nums.push(Math.floor(Math.random() * 10));
}
}
function displayNumbers() {
generateNumber();
for (let i of nums) {
const card = `<div class="card" onclick="flipCard(this)">
<div class="front">
<img src="/images/qmark.jpg" width="50px">
</div>
<div class="back">
<h2>${i}</h2>
</div>
</div>`
game.insertAdjacentHTML("beforeend", card);
}
}
displayNumbers();
function flipCard(elm) {
elm.classList.toggle("card-flip")
}
.card {
border: 1px solid black;
width: 100px;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
background-color: #444;
transition: transform 0.8s;
position: relative;
}
.card:hover {
background-color: #777;
}
.card-flip {
transition: 0.6s ease-in;
transform: rotateY(180deg);
}
.back,
.front {
position: absolute;
backface-visibility: hidden;
}
.back {
transform: rotateY(180deg);
}
<div class="contain">
<header>
<h1>Card Game</h1>
<button type="button" id="reset">Reset</button>
</header>
<div class="game"></div>
</div>
Answers(1)
Tolerim
a day ago
Verified Answer
It seems like you have a problem with CSS transition transform and rotateY(). Here's what you need to do:
- You need to give an initial value to the rotateY property. In your case, you can add transform: rotateY(0); in .card element, so it can rotate from front to back.
- You also need to specify the direction of the transform property, so it knows which way to spin. To specify the direction, use transform-origin property, which sets the origin of transformation for an element.
Here's the updated code for the .card class:
.card {
border: 1px solid black;
width: 100px;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
background-color: #444;
transform: rotateY(0); /* Add this line */
transition: transform 0.8s;
transform-origin: center right; /* Add this line */
position: relative;
}
After making these changes, your card should flip from front to back on click.