Friday, August 15, 2025

Bouncing Button with Direction Change

Full Code:


Demo :



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bouncing Button with Direction Change</title>
  <style>
    body {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background: #f0f0f0;
    }

    button {
      padding: 14px 28px;
      font-size: 18px;
      background: #007bff;
      color: white;
      border: none;
      border-radius: 10px;
      cursor: pointer;
      position: relative;
    }

    /* Bounce animation */
    @keyframes bounceRight {
      0%   { transform: translateX(0) scale(1); }
      30%  { transform: translateX(50px) scale(1.2); }
      50%  { transform: translateX(30px) scale(0.9); }
      70%  { transform: translateX(40px) scale(1.1); }
      100% { transform: translateX(0) scale(1); }
    }

    @keyframes bounceLeft {
      0%   { transform: translateX(0) scale(1); }
      30%  { transform: translateX(-50px) scale(1.2); }
      50%  { transform: translateX(-30px) scale(0.9); }
      70%  { transform: translateX(-40px) scale(1.1); }
      100% { transform: translateX(0) scale(1); }
    }

    .bounceRight {
      animation: bounceRight 0.6s;
    }

    .bounceLeft {
      animation: bounceLeft 0.6s;
    }
  </style>
</head>
<body>

  <button id="bounceBtn">Click Me</button>

  <script>
    const btn = document.getElementById("bounceBtn");
    let direction = true; // true = right, false = left

    btn.addEventListener("click", () => {
      if (direction) {
        btn.classList.add("bounceRight");
      } else {
        btn.classList.add("bounceLeft");
      }

      // toggle direction for next click
      direction = !direction;

      // remove class after animation so it can retrigger
      btn.addEventListener("animationend", () => {
        btn.classList.remove("bounceRight", "bounceLeft");
      }, { once: true });
    });
  </script>

</body>
</html>

No comments:

Post a Comment

  1. What is Google Opal? It’s a no-code / low-code AI mini-app builder developed by Google Labs. You describe what you want in natural ...