Is it possible to trigger this rotate function with a click on a button? with :active
it’s possible to rotate it by clicking on the box. But you will need to keep the button pressed; is it possible to have some kind of toggle function on :active?
Is there any JavaScript to make a box flip?
body {
font-family: Arial, Helvetica, sans-serif;
}
.flip-box {
background-color: transparent;
width: 300px;
height: 200px;
border: 1px solid #f1f1f1;
perspective: 1000px;
}
.flip-box-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.8s;
transform-style: preserve-3d;
}
.flip-box:hover .flip-box-inner {
transform: rotateY(180deg);
}
.flip-box-front,
.flip-box-back {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.flip-box-front {
background-color: #bbb;
color: black;
}
.flip-box-back {
background-color: dodgerblue;
color: white;
transform: rotateY(180deg);
}
<h1>3D Flip Box (Horizontal)</h1>
<h3>Hover over the box below:</h3>
<div class="flip-box">
<div class="flip-box-inner">
<div class="flip-box-front">
<h2>Front Side</h2>
</div>
<div class="flip-box-back">
<h2>Back Side</h2>
</div>
</div>
</div>
4
Answers
One approach is as below, with comments in the code to explain what’s going on:
JS Fiddle demo.
References:
<button>
.document.querySelector()
.document.querySelectorAll()
.Element.classList
.Element.closest()
.Element.querySelector()
.Element.querySelectorAll()
.Event
.EventTarget.addEventListener()
.This can be done without Javascript:
As long as you don’t care about IE,
classList
is a well-supported option.In your CSS file, change the following:
Then create a JavaScript file and add the following to it.
Then add the following
<script>
element to your html file.Here is the full code snippet:
Hope this helps.
.flip
class that does a 180deg turn of any element it is assigned to withtransform: rotateY(180deg)
.transform: rotateY(0deg)
to the class to be flipped (here.flip-box-inner
showing the ‘front’)..flip-box
)..flip
class on/off.UPDATE reply after OP comment
I replaced the snippet Javscript with jQuery syntax doing the same as the initial vanilla Javascript.