CSS3 ‘transitionend’ event
In the last article we’ve seen how to trigger CSS3 transitions with JavaScript. In this article we’ll go a bit further with CSS3 transitions. In this article we’ll see how to detect when a transition ends and how to do this in a cross browser compatible manner.
Basics
Assuming that we have a div element, whose id is ‘container’ and whose style is like the one we used in the first article:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#container { background-color: #FF0000; /* Default width and height */ width: 50px; height: 50px; /* Transition definition */ -webkit-transition: width 1s, height 2s); -moz-transition: width 1s, height 2s; -moz-transition: width 1s, height 2s; -o-transition: width 1s, height 2s; -ms-transition: width 1s, height 2s; transition: width 1s, height 2s; } |
When we run the following piece of JavaScript the defined transition will be triggered. Nothing new. This we have seen in the last article.
|
1 2 |
var elem = document.getElementById("container"); elem.setAttribute("style", "width: 150px; height: 150px"); |
But now we want to know when does the triggered transition end? To find this out we need to attach an event listener to the ‘transitionend’ event. Like this:
|
1 2 3 |
document.addEventListener("transitionend", function(e) { // Some useful code. }, true); |
The ‘transitionend’ fires for every property the transition has been applied to. So if we change both the width and the height the event will fire two times.
Cross browser compatibility
The ‘transitionend’ event only exists in Firefox. For webkit and Opera the event is named differently:
- Firefox: transitionend
- webkit: webkitTransitionEnd
- Opera: otransitioneend
So how do we normalize this? We don’t. What we gonna do is just attach a listener to all three events, like this:
|
1 2 3 4 5 6 7 |
function listener(e) { // Do something useful. } document.addEventListener("transitionend", listener, true); document.addEventListener("webkitTransitionEnd", listener, true); document.addEventListener("otransitionend", listener, true); |
No matter which browser is used only one event will fire at any given time. The other two will never fire because they don’t exist in that browser.
If you really want to normalize this you could use Modernizr to do that.
CSS shorthand notation
Take care when using CSS shorthand notation. For example: border: 1px solid #FFFFFF. This line alone will cause the event to fire two times. The shorthand notation will be broken down into: border-width and border-color. It’s logical but it can catch you off-guard.