Home > OS >  Changing animation-timing-function with Element.animate() in JavaScript
Changing animation-timing-function with Element.animate() in JavaScript

Time:02-02

I am trying to animate a HTML div using JavaScripts built in Element.animate() function. Sadly, I haven't found a way to change the animation-timing-function that is getting parsed along with other timing-settings as the second argument of the Element.animate() function.

My JavaScript code so far:

// This variable declares all keyframes of the animation.
const animationKeyframes = [
    {transform: 'translateY(-100%)'},
    {transform: 'translateY(0%)'}
]

// This variable contains all animation options.
// There should be a way to specify a timing-function.
const animationOptions = {
    duration: 1000,
    iterations: 1
}

// Runns the animation for the div that I want to animate.
Element.animate(animationKeyframes, animationOptions)

The code above executes without any errors and moves the div from the top to the bottom of the page at a linear speed. However, I want the speed to ease-in at the beginning and to ease-out at the end of the animation.

I tried:

  • adding animationTimingFunction: 'ease-in-out' to the animationTiming constant

  • adding animation-timing-function: ease-in-out; to the CSS properties of the div

My only source so far: Mozilla Docs: Element.animate()

CodePudding user response:

The issue is that Element.animate is not a native JavaScript method. The method you're looking for is element.animate.

Make sure to get the reference to the element you want to animate first, like this:

const animationKeyframes = [
    {transform: 'translateY(-100%)'},
    {transform: 'translateY(0%)'}
];

const animationOptions = {
    duration: 1000,
    iterations: 1,
    easing: 'ease-in-out'
};

const myDiv = document.querySelector('#myDiv');
myDiv.animate(animationKeyframes, animationOptions);
<div id="myDiv">Div to animate</div>

Or you can use CSS keyframes to animate the div with an ease-in-out timing function:

#myDiv {
  animation: myAnimation 1s ease-in-out 1;
}

@keyframes myAnimation {
  0% {
    transform: translateY(-100%);
  }
  100% {
    transform: translateY(0%);
  }
}

CodePudding user response:

You can just add the 'easing' prop in your animationOptions:

const animationOptions = {
    duration: 1000,
    iterations: 1,
    easing: 'ease-in-out'
}

Other values that can be used in the easing property are: 'ease', 'linear', 'ease-in', 'ease-out', and 'ease-in-out'.

  • Related