Web animation API event

96 Views Asked by At
<!DOCTYPE html>
<html>
<body>    
    <div id="div1"></div>
</body>
<script>
const Divtarget = document.getElementById("div1");
class animasi{
  constructor(){
   this.effect1 = [{width: "200px", 
      backgroundColor:"blue"},{width: "1000px"} ];
   this.opsi1 = {duration: 5000, fill:  "forwards",
     delay: 5000};
    }
}
const getanime = new animasi();
const keyframEffect1 = new KeyframeEffect(Divtarget,getanime.effect1,getanime.opsi1);
const animation1 = new Animation(keyframEffect1,document.timeline);

animation1.play();

Divtarget.addEventListener("animationend",function change(){
    const body = document.getElementById("body");
    body.style.backgroundColor = "red";
});

Divtarget.removeEventListener("animationend",function change(){
    const body = document.getElementById("body");
    body.style.backgroundColor = "red";
});
</script>
</html>

I want to use animationend event on web animation API, but when the animation is ended the call back function is not called. Why did this happen? Do animation events like animationstart, animationend, animationiteration, animationcancel work with an animation event?

1

There are 1 best solutions below

0
On

Add the 'finish' listener to the animation1

const Divtarget = document.getElementById("div1");
class animasi {
  constructor() {
    this.effect1 = [{
        width: "200px",
        backgroundColor: "blue"
      },
      {
        width: "1000px"
      }
    ];
    this.opsi1 = {
      duration: 1000,
      fill: "forwards",
      delay: 100
    };
  }
}
const getanime = new animasi();
const keyframEffect1 = new KeyframeEffect(Divtarget, getanime.effect1, getanime.opsi1);
const animation1 = new Animation(keyframEffect1, document.timeline);

// NOTE this
animation1.addEventListener('finish',  function change() {
  document.body.style.backgroundColor = "red";
});


animation1.play();
<div id="div1"></div>