Sometimes, we want to programmatically use CSS transitions with JavaScript.
In this article, we’ll look at how to programmatically use CSS transitions with JavaScript.
How to programmatically use CSS transitions with JavaScript?
To programmatically use CSS transitions with JavaScript, we can use an element’s animate
method.
For instance, we write:
<img src='https://www.macmillandictionary.com/external/slideshow/full/emoji_snowflake_full.jpg' style='width: 100px'>
to add an image to animate.
Then we write:
const snowFlake = document.querySelector('img')
const snowLeft = 200
const player = snowFlake.animate(
[{
transform: `translate(${snowLeft}px, -100%)'}`
},
{
transform: `translate(${snowLeft}px, ${window.innerHeight}px)`
}
],
1500);
setTimeOut(() => {
player.cancel();
}, 2000)
We select the image with document.querySelector
.
Then we call snowFlake.animate
with an array of key frames.
We set the transform
property to move the image.
And we specify the duration to be 1500ms.
Finally, we call player.cancel
to stop the animation after 2000ms.
Conclusion
To programmatically use CSS transitions with JavaScript, we can use an element’s animate
method.