Create a flip card using html css and javascript

Flip Card image Gif.
Flip Card image gif.

In today’s blog, I’ll show how we can create a Simple flip box using HTML, CSS, and a few lines of Javascript.

The flip box is common nowadays. Also, it’s not about the flip box if you understand the core concept you can create many different UI components using those few lines of code.

The core concept

How can I toggle between two classes on a button click? Let’s say you have two same-size cards with different HTML content now you want one of them to show and the second one to be hidden. once the user clicks on some button show the second card and hides the first one.

The solution!

Javascript is here to help. You can easily have a CSS class names .hidden with display: none; . The tricky part is adding and removing the class based on user events.

See the Pen Profile FlipBox by Dipankar Maikap (@dipankarmaikap) on CodePen.

As you can see in my above Codepen widget, I can click on the arrow button and it hides the first card and shows the second card and once I click on the follow button it hides the second card and opens the first card. You can check my HTML and CSS for the style and you will notice by default the second card have a hidden class. We have to toggle this class with javascript.

First step

Select both card containers and the buttons by their CSS Id.

var rightArrow = document.getElementById("arrow_button");
var topCard = document.getElementById("cover_image");
var bottomCard = document.getElementById("detail_content");
var followButton = document.getElementById("follow_button");

Second step

Add two event listeners to the two buttons and remove and add classes using classList.add and remove option.

rightArrow.addEventListener("click", function () {
  console.log("Hide top card and show bottom card.");
followButton.addEventListener("click", function () {
  console.log("Hide bottom card and show top card.");

That’s it now you can create a flip card using this. Also, you learned how you can add and remove classes of an element using javascript.

Stay safe and be happy. 🙂

Leave a Reply