Last Updated: September 29, 2021
·
2.076K
· zigotica

standarise TransitionEnd

If you ever tried to use a javascript callback to detect when a CSS transition was finished (ie after adding a class to an element), you would normally use something similar:

$(elm).addClass('active');
$(elm).one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function(e) {
    console.log("the end");
});

The problem with the code above is that some browsers will execute it twice, triggering event with and without prefix. To address this we can detect the appropriate event for the browser, then passing just that to the event manager.

After trying some tricks I found this is the simplest and most accurate way to do it:

var standartransitionend = (!!window.webkitURL)?'webkitTransitionEnd':'transitionend';
$(elm).addClass('active');
$(elm).one(standartransitionend, function(e) {
    console.log("the end");
});

The reasoning behind is that everyone is already using at least transitionend, but in webKit browsers (chrome, safari, opera) webkitTransitionEnd takes precedence.

PS: have not yet tried in IE/Win