JVPartanen
10/1/2017 - 6:32 AM

Detecting when a CSS keyframe animation has started, iterated, or ended OR transition has ended

We can use JavaScript to also detect when a CSS transition has ended, by tapping into the "transitionend" event. The caveat like setting CSS3 properties is that some older versions of Chrome and Safari still rely on the prefixed version of the event. To account for all the possible prefixes, we can use the following function to return the supported "transitionend" event in the browser:

http://www.javascriptkit.com/javatutors/css-transition-functions.shtml

function gettransitionend(){
    var root = document.documentElement
    var transitions = {
        'transition':'transitionend',
        'OTransition':'oTransitionEnd',
        'MozTransition':'transitionend',
        'WebkitTransition':'webkitTransitionEnd'
        }
     
    for (var t in transitions){
        if (root.style[t] !== undefined ){
            return transitions[t];
        }
    }
    return undefined
}
 
//Example Usage:
var transitionendevt = gettransitionend()
if (transitionendevt){ // if transitionend event supported by browser
    element.addEventListener(transitionendevt, function(e){
        // do something after end of transition
    }, false)
}
function getanimationevent(suffix){ // enter "start", "iteration", or "end"
    var root = document.documentElement
    var suffix = suffix.toLowerCase()
    var animations = {
        'animation': 'animation' + suffix,
        'OAnimation': 'oAnimation' + suffix.charAt(0).toUpperCase() + suffix.slice(1), // capitalize first letter of suffix
        'MozAnimation': 'animation' + suffix,
        'WebkitAnimation': 'webkitAnimation' + suffix.charAt(0).toUpperCase() + suffix.slice(1)
    }
     
    for (var a in animations){
        if (root.style[a] !== undefined ){
            return animations[a]
        }
    }
    return undefined
}
 
// getanimationevent('start') // returns supported version of "animationstart" event as a string
// getanimationevent('iteration') // returns supported version of "animationiteration" event as a string
// getanimationevent('end') // returns supported version of "animationend" event as a string
 
//Example usage:
var animationend = getanimationevent('end')
if (animationend ){
    element.addEventListener(animationend , function(e){
        // do something after end of keyframe animation
    }, false)
}