Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Forked from anonymous/index.html
Last active October 15, 2016 22:41
Show Gist options
  • Save christophemarois/8e61299439cb22eae14ea0afc863491a to your computer and use it in GitHub Desktop.
Save christophemarois/8e61299439cb22eae14ea0afc863491a to your computer and use it in GitHub Desktop.
Triggers a CSS animation from JS without class manipulation. Wrapped in a promise that resolves when animation is completed. Easily chainable. >IE10 when transpiled. Demo: http://jsbin.com/qibilaxehi
function animate (el, animationName, durationMs) {
return new Promise(res => {
const fn = e => {
if (!e.target.isEqualNode(el)) return false
el.removeEventListener('animationend', fn)
el.removeEventListener('webkitAnimationEnd', fn)
el.style.animationDuration = ''
el.style.webkitAnimationDuration = ''
el.style.animationName = ''
el.style.webkitAnimationName = ''
res(el)
}
el.addEventListener('animationend', fn)
el.addEventListener('webkitAnimationEnd', fn)
el.style.animationDuration = durationMs + 'ms'
el.style.webkitAnimationDuration = durationMs + 'ms'
el.style.animationName = animationName
el.style.webkitAnimationName = animationName
})
}
document.querySelector('a').addEventListener('click', e => {
let queue = Promise.resolve()
for (let h3 of document.querySelectorAll('h3')) {
queue = queue.then(() => animate(h3, 'pulse', 1000))
}
queue = queue.then(() => alert('done'))
})
<a href="#">click me</a>
<h3>We are gonna be animated one after the other</h3>
<h3>We are gonna be animated one after the other</h3>
<h3>We are gonna be animated one after the other</h3>
<h3>We are gonna be animated one after the other</h3>
<h3>We are gonna be animated one after the other</h3>
<h3>We are gonna be animated one after the other</h3>
@keyframes pulse {
from {
transform: scale(1);
transform-origin: center center;
animation-timing-function: ease-out;
}
25% {
transform: scale(1.1);
animation-timing-function: ease-in;
}
50% {
transform: scale(1);
animation-timing-function: ease-out;
}
74% {
transform: scale(1.05);
animation-timing-function: ease-in;
}
to {
transform: scale(1);
animation-timing-function: ease-out;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment