Add slide animation on button click
Lets say you wanted to add a slide animation to your website. You want to show up some content when a button is clicked or hovered or while we are loading the page.
The options we have using pure CSS + Vanilla javascript are to use the keyframes animation or using transition along with transition-duration property in CSS.
In this article , I will describe the things I came across and what I learnt . Almost all examples show how to transition on hover and on click . I needed the animation to run on load. So , I had this requirement where a button is clicked , a form from a different page is to be loaded with a slide-down transition. i.e, the form is revealed slowly height wise.
After a bit of trying out examples , it turns out we cannot use the transition property for this. keyframe animation is the one for this one .
Keyframe animation is pretty simple too . I had tried with multiple properties to get the affect that I was looking for. In the end, all looks simple but it took quite a bit of trying out .
For the final solution , it uses the animation of the max-height property and then the animation css can be used for multiple such elements. So , we use keyframe animation and say that over the duration the max-height will go from 0 to the max-height mentioned in a certain time duration.
Sample CSS :
@keyframes slide-down {
0% {
max-height: 0px;
opacity: 0;
}
100% {
max-height: 480px;
opacity: 1;
}
}.first-block-content {
height:300px; animation-duration: 5s;
animation-name: slide-down;
animation-timing-function: ease-out;
animation-iteration-count: 1;
animation-fill-mode: forwards;
}
So , to start with , we will give a div “first-block-content” a display:none , we will set it to visible when a button is clicked . We additionally add the keyframes animation and the animation property to the CSS of the first-block-content. What this does is , when the button is clicked , the content is made visible using the animation we have defined.
Add the animation to multiple elements
The same block of CSS as below when added to other elements would add the animation to those as well. Pls note that we are reusing the slide-down keyframe animation we created earlier.
animation-duration: 5s;
animation-name: slide-down;
animation-timing-function: ease-out;
animation-iteration-count: 1;
animation-fill-mode: forwards;
Full code can be found here : https://github.com/deepikagunda/slide-down-animation
Also include the browser-specific keyframe animations with their browser-specific transforms to help with cross browser compatibility . Can be found in github code above.
Additional Notes:
The animation can easily be changed for sliding up . For sliding left and sliding right using the max-width property etc. The duration can be customized , the pattern can be customized according to your needs.