Start with a button:
<button>Click me</button>
When someone clicks it, the button should spin in a circle and grow bigger. Here’s the CSS animation (generated by Animista):
.rotate-scale-up {
animation: rotate-scale-up 0.65s linear both;
}
/* ----------------------------------------------
* Generated by Animista on 2021-5-17 9:55:12
* Licensed under FreeBSD License.
* See http://animista.net/license for more info.
* w: http://animista.net, t: @cssanimista
* ---------------------------------------------- */
/**
* ----------------------------------------
* animation rotate-scale-up
* ----------------------------------------
*/
@keyframes rotate-scale-up {
0% {
transform: scale(1) rotateZ(0);
}
50% {
transform: scale(2) rotateZ(180deg);
}
100% {
transform: scale(1) rotateZ(360deg);
}
}
Adding the animation to the button
First, use the document.querySelector()
method to get the button
element. Then, add an event listener for click
events on it.
// Get the button
let button = document.querySelector('button');
// Listen for clicks on the button
button.addEventListener('click', function () {
// Do something when the button is clicked...
});
When the button
is clicked, use the classList.add()
method to add the .rotate-scale-up
class to the button
. This makes it rotate.
button.addEventListener('click', function () {
button.classList.add('rotate-scale-up');
});
Making the animation run more than once
button.addEventListener('click', function () {
button.classList.add('rotate-scale-up');
button.addEventListener('animationend', function () {
button.classList.remove('rotate-scale-up');
}, {once: true});
});
Here’s a helper function to wrap it all up:
/*!
* Apply a CSS animation to an element
* (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {Node} node The element to animate
* @param {String} animation The animation class to apply
* @param {Function} onEnd A callback function to run when the animation ends [optional]
*/
function animate (node, animation, onEnd = function () {}) {
node.classList.add(animation);
node.addEventListener('animationend', function () {
node.classList.remove(animation);
onEnd(node, animation);
}, {once: true});
}