Issue
I've got some buttons and if you click them they should rotate after which the backface displays the ::after pseudo element. The problem is that my code only applies tothe first button button.
The code i've written for flipping the button works, I just need to know how to apply it to the rest of the buttons:
const flip = document.querySelector(".reserve");
function buttonFlip() {
flip.classList.toggle("flip")
}
flip.addEventListener('click', () => {
buttonFlip();
});
.button {
position: relative;
transition: all .5s linear;
-webkit-transform-style: preserve-3d;
-webkit-backface-visibility: visible;
}
.button::after {
content: 'X';
transform: rotateY(180deg);
-webkit-transform-style: preserve-3d;
-webkit-backface-visibility: hidden;
background-color: #f00;
}
.flip {
transform: rotateY(180deg);
}
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
I know I should use queryselectorall but i'm not sure how to go about it as I'm a JS beginner and I'm trying to work out code from a logical standpoint. I've looked around SO and seen very similar questions, but when trying to apply them to my code it just never seems to work out quite right.
Solution
To target each individual button you can use querySelectorAll()
. From there you can loop over them all, attaching the click
event handler to each individual instance. From there you can use the target
property of the event that's raised to toggle the class on that element only:
const flipButtons = document.querySelectorAll(".reserve");
flipButtons.forEach(button => {
button.addEventListener('click', e => {
e.target.classList.toggle("flip")
})
});
// this is another version of the above as a one-liner
// flipButtons.forEach(button => button.addEventListener('click', e => e.target.classList.toggle("flip")));
.button {
position: relative;
transition: all .5s linear;
-webkit-transform-style: preserve-3d;
-webkit-backface-visibility: visible;
}
.button::after {
content: 'X';
transform: rotateY(180deg);
-webkit-transform-style: preserve-3d;
-webkit-backface-visibility: hidden;
background-color: #f00;
}
.flip {
transform: rotateY(180deg);
}
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
Answered By - Rory McCrossan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.