I have a problem with css rotate element from front to back with javascript. But I can't understand what is my mistake.
This is my basic HTML code. There is nothing wrong thing in here, but I don't know how rotate element works.
I want to rotate from front to back but it doesn't work. I want to create card that can rotate from front to back. When I want to click card, it should rotate around itself. But I can't do it.
Code
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>
You have to create the back and the front of the card, then flip the container
const button = document.querySelector(".btn-rotate");
const card = document.querySelector(".card");
button.addEventListener("click", function() {
if (card.className === "card back") {
card.className = "card front";
} else {
card.className = "card back";
}
});
.card {
height: 160px;
width: 100px;
position: relative;
transform-style: preserve-3d;
transition: transform 0.6s;
}
.card .front,
.card .back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 1px solid black;
border-radius: 8px;
backface-visibility: hidden;
}
.card.back {
transform: rotateY(180deg);
}
.card .back {
transform: rotateY(180deg);
}
.card .front {
background-color: black;
color: white;
}
.card .back {
background-color: white;
color: black;
}
<div class="card front">
<div class="front">Front</div>
<div class="back">Back</div>
</div>
<br/>
<button class="btn-rotate">Flip</button>