Easily wait for an element to CSS transition using native vanilla JavaScript
MIT License
Let's say you have the problem (that many of us have) where you need to wait for the completion of your element's
CSS transition
before your code continues. You can use this library and call a waitForElementTransition
method to wait until
the element finishes its css transition before doing other things in your javascript code.
transitionstart
and transitionend
eventsYou can either use the dist file directly in your project:
<script
type="text/javascript"
src="/dist/wait-for-element-transition.min.js"
></script>
Or install via npm
npm i wait-for-element-transition
and import
import waitForElementTransition from 'wait-for-element-transition';
Here's an example where we want to wait for an element's background color to change from black to red.
<style>
div {
background-color: black;
transition-property: background-color;
transition-duration: 100ms;
transition-timing-function: ease-out;
}
.red {
background-color: red;
}
</style>
<div>Transition this element</div>
<script
type="text/javascript"
src="/dist/wait-for-element-transition.min.js"
></script>
<script>
const element = document.querySelector('div');
element.classList.add('red'); // start transition
waitForElementTransition(element).then(() => {
// 100 milliseconds later...
console.log('element background color changed to red!');
});
</script>
If the element has already transitioned before the waitForElementTransition()
is called, the waitForElementTransition()
s
promise will resolve immediately. So you can always guarantee that your code will run, just as it would synchronously.
transitionend
eventUsing the transitionend
or animationend
events on an Element will allow you to wait until an Element's transition
has ended, but this approach is limited:
If done in a supported browser, the same thing in this package can be achieved using the Web Animations API. But consumers of this package may want a less-complex approach.
Watch source files while developing:
npm start
Run test
npm test