By default, CSS can start an animation on hover.
To start an animation based on a key press, you need JavaScript.
This library empowers CSS developers so you don't need to explicitly
write JS.
Add this to an HTML button
Start an animation from JavaScript events like onclick
, onkeydown
, onmouseout
Add animate="keydown"
(or whichever event type to listen to).
<button animate="click"> Click me </button>
Add your animation in CSS like normal
From your CSS file, add the CSS property --keydown-animation
(or --mouseout-animation
)
It's exactly the same as the animation: ;
property part of CSS.
button {
--click-animation: grow .2s ease-in;
}
@keyframes grow {
to { transform: scale(1.1); }
}
Two extra features to try
JavaScript events have more features than does :hover
or :focus
in CSS.
Here are two normally JS features this library brings to CSS:
- Show the JS event data on screen (like
.key
from akeydown
event) - Animate a parent element (e.g. animate the parent of a button, not the button itself)
- Add
animate-class="somecssclass"
to the parent you wish to animate - Add
animate="--somecssclass-keydown"
to the input/button that fires JS events
<div animate-class="trysample">
<h3> Welcome to our coffee shop! </h3>
<div>
<p> Would you like to try our daily special? </p>
<button animate="--trysample-click"> Try a sample </button>
</div>
</div>
- Add the class in CSS
.somecssclass { }
- Put any styles you want to apply when the event is fired
- (optional) you can target child elements (like
.somecssclass h3
)
.trysample {
box-shadow: 0 0 .25em .25em dodgerblue;
}
.trysample p {
animation: grow .2s ease-in-out;
}
Using these three steps, you can animate any element! A parent, a sibling, a child of the element that fires the JS event will work!
- To show data from a keypress or any event, add
-key
(for.key
data) - Your will look like:
<input animate="--myclass-keyup-key">
- The
animate-class
won't change!
<p> Each letter you type will briefly show up beside the input element. </p>
<div animate-class="type">
<p></p>
<input animate="--type-keydown-key">
</div>
- The data is now stored inside a CSS variable
- It has the same name as the animate attribute:
var(--myclass-keyup-key)
- Use the CSS feature "pseudo-elements" (
::before
) to show the data on screen
.type p::before {
content: var(--type-keydown-key);
}