I'm trying to make a div flip once a button has been clicked, but it doesn't seem to be working correctly and I can't figure out why. I was wondering if anybody would be able to point me in the right direction and correct my errors.
My code:
var init = function() {
var card = document.getElementById('card');
document.getElementById('flip').addEventListener('click', function() {
card.toggleClassName('flipped');
}, false);
};
window.addEventListener('DOMContentLoaded', init, false);
.container {
width: 200px;
height: 260px;
position: relative;
perspective: 800px;
}
#card {
width: 100%;
height: 100%;
position: absolute;
transform-style: preserve-3d;
transition: transform 1s;
}
#card figure {
margin: 0;
display: block;
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
#card .front {
background: red;
}
#card .back {
background: blue;
transform: rotateY(180deg);
}
#card.flipped {
transform: rotateY(180deg);
}
<section class="container">
<div id="card">
<figure class="front">1</figure>
<figure class="back">2</figure>
</div>
</section>
<section id="options">
<p>
<button id="flip">Flip Card</button>
</p>
</section>
You can find a JSFiddle here.
Thank you.
There were two things keeping your code from running:
JSFiddle runs JavaScript in onLoad
by default, which is after the DOMContentLoaded
event that you're waiting for, so remove that for the purposes of the JSFiddle only.
There is no toggleClassName
function in vanilla JavaScript to the best of my knowledge. Instead I've changed it to toggle using the class list.
Here is the fixed and working code. I've shortened the box's height so it fits better in the demo box.
Live Demo:
var card = document.getElementById('card');
document.getElementById('flip').addEventListener('click', function() {
card.classList.toggle('flipped');
}, false);
.container {
width: 200px;
height: 100px;
position: relative;
perspective: 800px;
}
#card {
width: 100%;
height: 100%;
position: absolute;
transform-style: preserve-3d;
transition: transform 1s;
}
#card figure {
margin: 0;
display: block;
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
#card .front {
background: red;
}
#card .back {
background: blue;
transform: rotateY( 180deg);
}
#card.flipped {
transform: rotateY( 180deg);
}
<section class="container">
<div id="card">
<figure class="front">1</figure>
<figure class="back">2</figure>
</div>
</section>
<section id="options">
<p>
<button id="flip">Flip Card</button>
</p>
</section>
JSFiddle Version: https://jsfiddle.net/dL9v1ozf/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With