So I wanted to open a dialog in the community about various techniques people have used to detect when an animation is ended. Particularly when fading something out (read opacity).
Now I am not sure what other people have used, but I have found it particularly effective to use a timeout to wait for the animation to end, and then hide it, like so (using jQuery obviously):
$('#someDiv').css({'opacity':0});
setTimeout(function(){$('#someDiv').hide()}, 500);
where the CSS looks like this:
#someDiv {
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
-o-transition: opacity 0.5s ease-in-out;
-ms-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
I am aware of the transition end bindings that most of the modern browsers have implemented, but I seriously dislike using them. The seem a bit flaky and I hate having to loop over and set the listeners up. Plus with each browser having a totally different event fired, it gets hairy.
What are some thoughts on the various techniques that are out there? Since this is relatively new and undocumented, let's see what people have been using!
Thanks guys! -Geoff
There is an event for this called
transitionend
which makes much more sense than to use a setTimeout
.
So you should go like
$('#someDiv').css({'opacity':0}).on('transitionend', function(e) {
$(this).hide();
});
Since the name for that event-type can vary between browsers, I wrote a little helper:
var dummy = document.createElement( 'div' ),
eventNameHash = { webkit: 'webkitTransitionEnd', Moz: 'transitionend', O: 'oTransitionEnd', ms: 'MSTransitionEnd' },
transitionEnd = (function _getTransitionEndEventName() {
var retValue = 'transitionend';
Object.keys( eventNameHash ).some(function( vendor ) {
if( vendor + 'TransitionProperty' in dummy.style ) {
retValue = eventNameHash[ vendor ];
return true;
}
});
return retValue;
}());
So use that code to advance-conditional load the correct event name and then use the transitionEnd
variable for the .on()
binding name.
Example: http://jsfiddle.net/QBFtH/1/
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