Reputation: 859
How to detect that the animation reached a specific keyframe? (For example 50% or 75%).
This is what I tried:
element.addEventListener("animationend", AnimationListener, false);
but it supports animationstart, animationiteration and animationend only.
http://jsfiddle.net/W3y7h/294/
Upvotes: 1
Views: 227
Reputation: 6796
Using the example Fiddle provided, what you're essentially looking to know is when the value of #sun
element's bottom
property is equal to 100px
. You can do this by using getComputedStyle()
to check that value, clearing the interval when it is equal to 100px
and then executing whatever code you wish, like so:
var style=window.getComputedStyle(document.getElementById("sun")),
interval=setInterval(function(){
if(parseInt(style.getPropertyValue("bottom"))===100){
clearInterval(interval);
console.log("50% reached");
}
},1);
#sun{
animation:sunrise 1s ease;
bottom:0;
background:#ff0;
border-radius:50%;
height:50px;
position:absolute;
width:50px;
}
@keyframes sunrise{
0%{
bottom:0;
left:0;
}
50%{
bottom:100px;
}
100%{
bottom:0;
left:400px;
}
}
<div id="sun"></div>
To check for multiple values, simply set a new interval. In the case of your example, the value of the bottom
property should be 50px
when the animation is 75% complete. That being said, it may not always be exactly 50px
in every browser so, instead, given that we know the value of the bottom
property will be decreasing at this point, instead check for it being less than or equal to 50:
var style=window.getComputedStyle(document.getElementById("sun")),
interval=setInterval(function(){
if(parseInt(style.getPropertyValue("bottom"))===100){
clearInterval(interval);
console.log("50% reached");
interval=setInterval(function(){
if(parseInt(style.getPropertyValue("bottom"))<=50){
clearInterval(interval);
console.log("75% reached");
}
},1);
}
},1);
#sun{
animation:sunrise 1s ease;
bottom:0;
background:#ff0;
border-radius:50%;
height:50px;
position:absolute;
width:50px;
}
@keyframes sunrise{
0%{
bottom:0;
left:0;
}
50%{
bottom:100px;
}
100%{
bottom:0;
left:400px;
}
}
<div id="sun"></div>
Upvotes: 2