Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

create a ball that bouncing up and down when i clicked using HTML, CSS, and JS.

  1. User

    create a ball that bouncing up and down when i clicked using HTML, CSS, and JS.

  2. Assistant

    Creating an interactive ball that bounces up and down when clicked can be a fun exercise to work with HTML, CSS, and JavaScript. Here’s a simple example of how you can create this effect:

    HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bouncing Ball</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div id="ball" class="ball"></div>
        
        <script src="script.js"></script>
    </body>
    </html>
    

    CSS (styles.css)

    body, html {
        height: 100%;
        margin: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f0f0;
    }
    
    .ball {
        width: 50px;
        height: 50px;
        background-color: #ff6347;
        border-radius: 50%;
        position: relative;
        cursor: pointer;
        animation: bounce 0s linear infinite;
    }
    
    @keyframes bounce {
        0%, 20%, 50%, 80%, 100% {
            transform: translateY(0);
        }
        40% {
            transform: translateY(-150px);
        }
        60% {
            transform: translateY(-75px);
        }
    }
    

    JavaScript (script.js)

    const ball = document.getElementById('ball');
    let isBouncing = false;
    
    ball.addEventListener('click', () => {
        if (isBouncing) {
            ball.style.animation = "bounce 0s linear infinite";
            isBouncing = false;
        } else {
            ball.style.animation = "bounce 2s linear infinite";
            isBouncing = true;
        }
    });
    

    Explanation

    1. HTML: We create a basic structure with a div element representing the ball.

    2. CSS:

      • The .ball class styles the ball to be round and centered on the page.
      • The @keyframes bounce sets up a bounce animation using keyframes to simulate a bouncing effect by changing translateY positioning.
    3. JavaScript:

      • We add an event listener to the ball that toggles the animation on and off when clicked.
      • The isBouncing flag helps manage the state to know whether the ball is currently bouncing or not.

    By clicking the ball, you start or stop the bounce effect. The animation duration can be adjusted by changing the 2s value in the JavaScript part for faster or slower bounces.