Home > OS >  How to filp to the back of a card to display text using JavaScript
How to filp to the back of a card to display text using JavaScript

Time:12-17

I created a card on HTML and CSS, and using JavaScript I want to be able to flip the card so it shows the back of the card which will display different info from the front.

How would I go about doing that on JavaScript?

Haven't tried yet just wanted to work through the problem.

CodePudding user response:

I will not bring you the entire solution, because you aren't showing any code.

But i finded on internet these steps to seem legit to archive what you want:

  1. Add a "flip" button or some other element that the user can click to trigger the flip action.
  2. Add a CSS class to your card element that defines the styles for the flipped state. For example, you might want to rotate the card 180 degrees and display the back of the card.
  3. Add a click event listener to the flip button or element.
  4. In the event handler function for the click event, use classList.toggle to add or remove the CSS class that defines the flipped state. You can use the transition property in your CSS to animate the flip effect.

If you are in trouble with the code, you can show us and maybe we can help you more in deep. Best of luck!

PS: You can find all these information just using google, it's not necessary to come here to be honest.

CodePudding user response:

Here you can try this logic :

 let flip = document.querySelector(".flip");
      let degInc = 180;

      let isFlip = false;

      function flipFn(ev) {
        let styles = {
          transform: `rotateY(${degInc}deg)`,
        };
        Object.assign(flip.style, styles);

        flipChild = {
          display: `${!isFlip ? "block" : "none"}`,
          transform: `rotateY(${-degInc}deg)`,
        };

        setTimeout(() => {
          Object.assign(document.querySelector(".flip > *").style, flipChild);
        }, 300);

        if (!isFlip) {
          isFlip = true;
          degInc  = 180;
        } else {
          isFlip = false;
          degInc -= 180;
        }
      }
   .flip {
      width: 200px;
      height: 200px;
      background-color: yellow;
      z-index: 1;
      transition: 0.3s ease-in-out;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .flip > * {
      display: none;
    }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div >
      <h2>HELLO</h2>
    </div>
    <button onclick="flipFn(event)">flip</button>
    
  </body>
</html>

  • Related