Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a div flip on button press?

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.

like image 742
junoprobelaunch Avatar asked Jun 03 '16 01:06

junoprobelaunch


1 Answers

There were two things keeping your code from running:

  1. 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.

  2. 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/

like image 159
Maximillian Laumeister Avatar answered Sep 22 '22 05:09

Maximillian Laumeister