Sometimes, we may want to run JavaScript code when a CSS transition finishes.
In this article, we’ll look at how to run a JavaScript callback when a CSS3 transition finishes.
Listen to the transitionend Event
To run JavaScript code when a CSS3 transition finishes, we can listen to the transitionend
event.
For instance, if we have the following HTML:
<div id="my-div">Click me to start animation.</div>
And the following CSS:
#my-div {
transition: top 2s;
position: relative;
top: 0;
}
div {
background: #ede;
cursor: pointer;
padding: 20px;
}
Then we can add a click event listener to apply the transition and update the div’s content when the transition is done by writing:
const myDiv = document
.getElementById("my-div")
myDiv
.addEventListener("transitionend",
() => {
myDiv.innerHTML = "transition event ended";
})
myDiv
.addEventListener('click', () => {
myDiv.style.top = '55px'
})
First, we have the div with ID my-div
with document.getElementById
.
Then we call addEventListener
on the returned div with the 'transitionend'
string to add a transitionend
event listener.
In the event handler function, we update its innerHTML
to 'transition event ended'
.
Then we add a click
event listener to the same div to set the top
CSS property to '55px'
.
In the CSS, we add a transition
property to add some transition effect when we change the top
property.
And the effect will last 2 seconds.
Now when we click on the div, it’ll side down. And the text content will become ‘transition event ended’ because the transitionend
event listener ran.
Conclusion
We can listen to the transitonend
event to run JavaScript code when a CSS3 transition ends.