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:

When we run the following piece of JavaScript the defined transition will be triggered. Nothing new. This we have seen in the last article.

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:

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:

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.

Comments are closed.