Polymer 2.0: Replace <neon-animation> with Web Animations API
The <neon-animation> element got deprecated with Polymer 2.0. Here are the steps to replace it with the Web Animation API.
The past: Neon-animations
For illustration, here is a simple element using the deprecated neon-animations:
<dom-module id="my-element">
<template>
<style>
#animatable {
background: red;
}
</style>
<div id="animatable">I'm animated!</div>
</template> <script>
class MyElement extends
Polymer.mixinBehaviors([Polymer.NeonAnimationRunnerBehavior],
Polymer.Element) {
static get is() {
return 'my-element';
} show() {
this.playAnimation();
}
getAnimationConfig() {
return [{
name: 'slide-down-animation',
node: this.$.animatable,
timing: {
duration: 500
}
},
{
name: 'slide-up-animation',
node: this.$.animatable,
timing: {
delay: 1000,
duration: 500
}
}];
}
}
customElements.define(MyElement.is, MyElement);
</script>
</dom-module>
On calling the show()
method, the element will slide down, be visible for 0.5 sec, and then fade out.
The future: Web Animation API
Let’s convert this element to use the Web Animations API:
class MyElement extends Polymer.Element {
static get is() {
return 'my-element';
} show() {
this.$.animatable.animate([
{transform:'translateY(0)', opacity: 1, easing: 'ease-out'},
{transform:'translateY(100%)', opacity: 1, easing: 'ease-in'},
{transform:'translateY(100%)', opacity: 0 }
],
{
duration: 1500,
});
}
}
customElements.define(MyElement.is, MyElement);
There is a catch tough: Some of the major browsers, like Edge and Safari, don’t support the Web Animations API today. Luckily, there is a polyfill, which you can install to your project:
bower install web-animations-js
And then add to your element:
<link rel="import" href="bower_components/neon-animation/web-animations.html">
Preserve animation end state
There is one more challenge left: The element returns to its original state once the animation finishes. In our example, the element jumps back to the top and is again visible. With neon-animations, you could listen to the neon-animation-finish
event and permanently change the element.
The Web Animations API offers the same functionality via animation.finished
, a promise that resolves when the animation finishes.
To preserve the end state of our animation, we simply need to fix the state:
show() {
const animation = this.$.animatable.animate([
{transform:'translateY(0)', opacity: 1, easing: 'ease-out'},
{transform:'translateY(100%)', opacity: 1, easing: 'ease-in'},
{transform:'translateY(100%)', opacity: 0 }
],
{
duration: 1500,
});
animation.finished.then(() => {
// Preserve end position of the animation
this.$.animatable.style.transform = 'translateY(100%)';
this.$.animatable.style.opacity = 0;
});
}
Happy coding!
Want to learn more about Polymer? Have a look to all our Medium posts on Polymer.
Photo: Peter Jackson