Last active
January 31, 2023 15:49
-
-
Save davej/44e3bbec414ed4665220 to your computer and use it in GitHub Desktop.
Do a CSS transition and resolve promise when complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const transitionToPromise = (el, property, value) => | |
new Promise(resolve => { | |
el.style[property] = value; | |
const transitionEnded = e => { | |
if (e.propertyName !== property) return; | |
el.removeEventListener('transitionend', transitionEnded); | |
resolve(); | |
} | |
el.addEventListener('transitionend', transitionEnded); | |
}); | |
/* | |
CSS rule: | |
#main-nav { | |
opacity: 0; | |
transition: opacity 1s; | |
} | |
*/ | |
// Usage | |
const mainNav = document.getElementById('main-nav'); | |
function es2015() { | |
transitionToPromise(mainNav, 'opacity', '1') | |
.then(() => alert('Transition done')); | |
} | |
async function es2016() { | |
await transitionToPromise(mainNav, 'opacity', '1'); | |
alert('Transition done'); | |
} |
Very useful! Thanks!
very good
Saved my life big time!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rad.