Search code examples
javascripthtmlcssanimationflip

animation Flip div when clicked


I am trying to make the divs flip whenever I click on them. I'm not sure why it doesn't work. Please help.

Here is the demo of this code. http://langbook.co/testicles-1-2-flashcards/

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#flip3D{ width:240px; height:200px; margin:10px; float:left; }
#flip3D > #front{
position:absolute;
transform: perspective( 600px ) rotateY( 0deg );
background:#FC0; width:240px; height:200px; border-radius: 7px;
backface-visibility: hidden;
transition: transform .5s linear 0s;}
#flip3D > #back{
position:absolute;
transform: perspective( 600px ) rotateY( 180deg );
background: #80BFFF; width:240px; height:200px; border-radius: 7px;
backface-visibility: hidden;
transition: transform .5s linear 0s;}
</style>
<script>
function flip(el){
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";}
var vlib = document.getElementById('front');
vlib.addEventListener(click, flip(el));
</script>
<title>Flashcards</title>
</head>
<body>
<div id="flip3D">
  <div id="back">Box - Back</div>
  <div id="front">Box - Front </div>
</div>
</body>
</html>

Solution

  • First, I would move your JS to the end of the page.

    It also seems like you want to be calling flip() on #flip3D, because you are trying to access it's child elements, like so:

    var vlib = document.getElementById('flip3D');
    vlib.addEventListener('click', flip(vlib));
    

    To flip back, you could just keep the object's state in an attribute to know which side it's on. Also note that flip(vlib) will be called immediately; to wait for the click event, you'll need to pass a reference to the function:

    vlib.addEventListener('click', flip);
    

    Seems to work: JSFiddle