I have a div with an animation.
I've attached an animationend event listener to this div.
This div also has a child element with an animation.
For some reason the animationend event fires when the childelement's animation finishes as well.
Why is this? Is there a way to get around this? I would like the animationend event only to run when the element that I attached the eventlistener to finishes.
document.querySelector('.outer').addEventListener('animationend',function () {
console.log('done')
})
body {
height:100vh;
display:grid;
place-items:center;
}
.outer {
display:grid;
place-items:center;
height:200px;
width:200px;
background:black;
animation:spin 2s
}
.inner {
height:50px;
width:50px;
background:red;
animation:spin 2s 2s
}
@keyframes spin {
from {
transform:rotate(0)
}
to {
transform:rotate(360deg)
}
}
<div class="outer">
<div class="inner">
</div>
</div>
Trying with id instead. Still no luck
document.querySelector('#outer').addEventListener('animationend',function () {
console.log('done')
})
body {
height:100vh;
display:grid;
place-items:center;
}
#outer {
display:grid;
place-items:center;
height:200px;
width:200px;
background:black;
animation:spin 2s
}
.inner {
height:50px;
width:50px;
background:red;
animation:spin 2s 2s
}
@keyframes spin {
from {
transform:rotate(0)
}
to {
transform:rotate(360deg)
}
}
<div id="outer">
<div class="inner">
</div>
</div>
You can check if the event's target is the element the listener is attached to. The event handler is also called when the animation on a child element ends because the animationend event bubbles.
document.querySelector('.outer').addEventListener('animationend', function(e) {
if(e.target === this) console.log('done')
})
document.querySelector('.outer').addEventListener('animationend',function (e) {
if(e.target === this) console.log('done')
})
body {
height:100vh;
display:grid;
place-items:center;
}
.outer {
display:grid;
place-items:center;
height:200px;
width:200px;
background:black;
animation:spin 2s
}
.inner {
height:50px;
width:50px;
background:red;
animation:spin 2s 2s
}
@keyframes spin {
from {
transform:rotate(0)
}
to {
transform:rotate(360deg)
}
}
<div class="outer">
<div class="inner">
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With