Hello Everyone! I’ve recently ran into a problem. I left the codepen link https://codepen.io/adamlohrman/pen/oRyQay. What I’m trying to do, make the cards flip, individually and I keep running into problems. If anyone could give me some feedback on what they would do, it would be greatly appreciated! I either get all of the cards to flip at the same time, or just the first one flips. I would be forever in your debt! Thanks!
You can use the click event to get to the DOM elements.
function cardFlopper(e) {
// edit check the target first
if (e.target.className !== 'front' && e.target.className !== 'back') return;
const parentTarget = e.target.parentElement;
const back = e.target.previousElementSibling;
if (parentTarget.style.transform === "rotateY(180deg)") {
parentTarget.style.transform = "rotateY(0deg)";
} else {
parentTarget.style.transform = "rotateY(180deg)";
back.style.transform = "rotateY(180deg)";
}
}
So what you need to do is add the click events to the individual cards.
What you’re currently doing is placing a box around both cards and adding the click event to that box. And whenever that box is clicked it changes all the cards state to its inverse state.
I’m not a big fan of how you named your classes, but what you’re looking for is this:
Note: delete all your current javascript and add below.
const $allCards = document.querySelectorAll(".noClass");
Array.from($allCards).forEach(($card) => {
$card.addEventListener('click', cardFlopper);
});
function cardFlopper(evt) {
const $clickedCard = evt.target.closest('.noClass');
$clickedCard.querySelector('.innerFlip').classList.toggle('rotate');
$clickedCard.querySelector('.back').classList.toggle('rotate');
}
.rotate {
transform: rotateY(180deg);
}
.back {
position: absolute;
width: 150px;
height: 150px;
background-color: black;
color: white;
backface-visibility: hidden;
transform: rotateY(180deg); <----- add this
}
.innerFlip {
position: relative;
width: 150px;
height: 150px;
transition: transform 0.8s;
transform-style: preserve-3d;
transform: rotateY(0deg); <------ add this
}
You should always try to stay away from changing CSS with javascript. Instead,. give those css properties to a class and use JS to add/remove those classes to the specific DOM element.
Reasoning:
Nothing overwrites JS changing your CSS except !important.
Hello kerafyrm02. Thank you for your reply, I’ll definitely be making the changes. I’m not very familiar with DOM manipulation as I’d like to be and you answered a lot of questions for me. About the class names, I’m not a big fan either. It’s part of a much larger application that I’m working on and just wrote it by itself to get some help on it. Anyways, thanks again for the help.