The transitionend
event is fired when a CSS transition has completed. In the case where a transition is removed before completion, such as if the transition-property
is removed or display
is set to none
, then the event will not be generated.
The transitionend
event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the transitioncancel
event is fired, the transitionend
event will not fire.
This code gets an element that has a transition defined and adds a listener to the transitionend
event:
const transition = document.querySelector('.transition');
transition.addEventListener('transitionend', () => {
console.log('Transition ended');
});
The same, but using the ontransitionend
:
const transition = document.querySelector('.transition');
transition.ontransitionend = () => {
console.log('Transition ended');
};
In the following example, we have a simple <div>
element, styled with a transition that includes a delay:
<div class="transition">Hover over me</div>
<div class="message"></div>
.transition {
width: 100px;
height: 100px;
background: rgba(255,0,0,1);
transition-property: transform, background;
transition-duration: 2s;
transition-delay: 1s;
}
.transition:hover {
transform: rotate(90deg);
background: rgba(255,0,0,0);
}
To this, we'll add some JavaScript to indicate that the transitionstart
, transitionrun
, transitioncancel
and transitionend
events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends.
const message = document.querySelector('.message');
const el = document.querySelector('.transition');
el.addEventListener('transitionrun', function() {
message.textContent = 'transitionrun fired';
});
el.addEventListener('transitionstart', function() {
message.textContent = 'transitionstart fired';
});
el.addEventListener('transitioncancel', function() {
message.textContent = 'transitioncancel fired';
});
el.addEventListener('transitionend', function() {
message.textContent = 'transitionend fired';
});
The transitionend
event is fired in both directions: when the box finishes turning and the opacity hits 0 or 1, depending on the direction.
If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired.
If the transitioncancel
event is fired, the transitionend
event will not fire.