Trigger animations with button press

Trigger animations with button press
0

#1

Is there a way i can trigger an animation on a button press?

This animation won’t be for the button itself, rather for another element.

If i had a box with a button below it, me clicking on that button would cause a animation to activate in which the box’s with is now 1000px.

Would i have to do this in JS using jquery? If so how do i do it either way?


#2

Is it a CSS animation? Or are you wanting to animate using JavaScript/jQuery?


#3

I have a css animation to change the height of a box. How would i trigger that animation when i push a button, which is a separate element?

Is there a way to do this with css, or would i have to use jQuery? Like adding classes for instance.


#4

Let’s say you had the following box and button along with the CSS to animate the box.

HTML

<div class="box"></div>
<button id="btn">Click Me</button>

CSS

body {
  text-align: center;
}

#btn {
  display: block;
  margin: auto;
}

.box {
  -webkit-transition: all 2s ease;  
  -moz-transition: all 2s ease;  
  -o-transition: all 2s ease;  
  -ms-transition: all 2s ease;  
  transition: all 2s ease;  
  display: inline-block;
  background-color: black;
  height: 100px;
  width: 100px;
  margin: 10px auto;
}

.grow {
  width: 1000px;
}

You could then write the following vanilla JavaScript to activate the animation on the box.

document.getElementById('btn').addEventListener('click', function () {
  document.querySelector('.box').classList.add('grow');
});

#5

Is there anyway i can do this keyframes? transitions is kinda confusing.


#6

I was under the impression that you already had created the CSS to animate your box and just wanted to know how to activate based on clicking a button.


#7

This was my keyframe:

@keyframes changeHeight {
  25% {
    height: 600px;
  }
  50% {
    height: 500px;
  }
  100% {
    height: 1000px;
  }
}

I wanted to activate it on a box, with a button. What is the best way in css/js?


#8

You did not say what you want to happen after the animation completes. Do you want the box to stay at the expanded height? If so, the following CSS would work using the same HTML and JavaScript I previously posted.


body {
  text-align: center;
}

#btn {
  display: block;
  margin: auto;
}

.box {
  display: inline-block;
  background-color: black;
  height: 100px;
  width: 100px;
  margin: 10px auto;
}

.grow {
  animation-duration: 2s;
  animation-name: changeHeight;
  animation-fill-mode: forwards;
}

@keyframes changeHeight {
  25% {
    height: 600px;
  }
  50% {
    height: 500px;
  }
  100% {
    height: 1000px;
  }
}