Webkit's transition end event is called webkitTransitionEnd, Firefox is transitionEnd, opera is oTransitionEnd. What is a good way of tackling all of them in pure JS? Should I do browser sniffing? or implement each one separately? Some other way that hasn't occurred to me?
i.e.:
//doing browser sniffing var transitionend = (isSafari) ? "webkitTransitionEnd" : (isFirefox) ? "transitionEnd" : (isOpera) ? "oTransitionEnd"; element.addEventListener(transitionend, function(){ //do whatever },false);
or
// Assigning an event listener per browser element.addEventListener("webkitTransitionEnd", fn); element.addEventListener("oTransitionEnd", fn); element.addEventListener("transitionEnd", fn); function fn() { //do whatever }
CSS3 Transitions element is supported by all Microsoft Edge browser.
If you have a transition not working, check that the starting value of the property is explicitly set. Sometimes, you'll want to animate height and width when the starting or finishing value is auto . (For example, to make a div collapse, when its height is auto and must stay that way.)
There's a technique used in Modernizr, improved:
function transitionEndEventName () { var i, undefined, el = document.createElement('div'), transitions = { 'transition':'transitionend', 'OTransition':'otransitionend', // oTransitionEnd in very old Opera 'MozTransition':'transitionend', 'WebkitTransition':'webkitTransitionEnd' }; for (i in transitions) { if (transitions.hasOwnProperty(i) && el.style[i] !== undefined) { return transitions[i]; } } //TODO: throw 'TransitionEnd event is not supported in this browser'; }
Then you can just call this function whenever you need the transition end event:
var transitionEnd = transitionEndEventName(); element.addEventListener(transitionEnd, theFunctionToInvoke, false);
As per Matijs comment, the easiest way to detect transition events is with a library, jquery in this case:
$("div").bind("webkitTransitionEnd.done oTransitionEnd.done otransitionend.done transitionend.done msTransitionEnd.done", function(){ // Unlisten called events by namespace, // to prevent multiple event calls. (See comment) // By the way, .done can be anything you like ;) $(this).off('.done') });
In library-less javascript it gets a bit verbose:
element.addEventListener('webkitTransitionEnd', callfunction, false); element.addEventListener('oTransitionEnd', callfunction, false); element.addEventListener('transitionend', callfunction, false); element.addEventListener('msTransitionEnd', callfunction, false); function callfunction() { //do whatever }
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