skip to Main Content

Sup, guys!

Im learning css, and im trying to figure out how to animate a div with a separate button

I just can’t figure out how to use the button as a trigger

Here’s an example

    <!-- html -->

<button id="mybutton">click me!</button><br>

<h1><div id="mydiv">hi</div></h1>

And my css

    #mydiv{
       border: 1px solid black;
       height: 100px;
       width: 100px;
       background: green;
   }
   

I didn’t add the keyframes and animations here, but what im trying to do when i press the button the div or "hi" slides from the bottom to top or something as long as it’s an animation

2

Answers


  1. The HTML sets up a button and a container for the sliding div. Styling ensures the sliding div starts at the bottom, transitions on the transform property create the sliding effect, and the slide-up class moves the div upward. Clicking the button toggles the slide-up class, animating the div up, and a timeout returns it to the original position after the animation duration.

    const button = document.getElementById('mybutton');
    const myDiv = document.getElementById('mydiv');
    
    button.addEventListener('click', () => {
      myDiv.classList.toggle('slide-up');
      setTimeout(() => {
        myDiv.classList.toggle('slide-up');
      }, 1000); // Match the duration of the transition
    });
    #container {
      height: 200px; /* Adjust the container's height as needed */
      overflow: hidden;
      position: relative;
    }
    
    #mydiv {
      border: 1px solid black;
      height: 100px;
      width: 100px;
      background: green;
      position: absolute;
      bottom: 0;
      transition: transform 1s ease-out;
    }
    
    .slide-up {
      transform: translateY(-100%);
    }
     <button id="mybutton">Click me!</button><br>
    <h1><div id="mydiv" class="hidden">hi</div></h1>
    Login or Signup to reply.
  2. You’re going to need to use javascript to add an event listener to the button and apply the animation to the div.

    CSS

    #mydiv {
        border: 1px solid black;
        height: 20px;
        width: 20px;
        background: green;
        position: relative;
        top: 0;
        transition: top 1s;
    }
    
    #mydiv.animate {
        top: -100px;
    }
    

    HTML

    <button id="mybutton">click this</button><br>
    <div id="mydiv">hi</div>
    

    JS

    document.getElementById('mybutton').addEventListener('click', function() {
        var myDiv = document.getElementById('mydiv');
        myDiv.classList.toggle('animate');
    });
    

    I made a JSFiddle for you to look at and build off of

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search