Skip to content

Instantly share code, notes, and snippets.

@ceceppa
Last active May 9, 2020 09:09
Show Gist options
  • Select an option

  • Save ceceppa/03e85b6b5d808147016c8b21be1897bd to your computer and use it in GitHub Desktop.

Select an option

Save ceceppa/03e85b6b5d808147016c8b21be1897bd to your computer and use it in GitHub Desktop.
Wait for jQuery transition to finish before applying the next chained command
function whichTransitionEvent() {
let t;
const el = document.createElement('fakeelement');
const transitions = {
transition: 'transitionend',
OTransition: 'oTransitionEnd',
MozTransition: 'transitionend',
WebkitTransition: 'webkitTransitionEnd',
};
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
return null;
}
/**
* Wait for css transition.
*
* When using css3 animations is not possible chain multiple events.
* For example if we want to hide/show an/the element when the animation is completed, we
* need to use one or more setTimeout to accomplish that. Also if need to change the
* duration of the animation, we also have to change the duration used for the
* setTimeout.
*
* Example:
*
* $('element').addClass('flip');
*
* setTimeout(function() {
* $('element').hide();
* }, 300);
*
* The following code allow us to easily chain multiple jQuery functions, example:
*
* $('element').addClass('flip').waitTransition().hide();
*
* or
*
* $('element').addClass('flip').waitTransition($el => $el.hide());
*/
// eslint-disable-next-line
jQuery.fn.waitTransition = function (callback) {
const transitionEnd = whichTransitionEvent();
this.each((i, el) => {
const $el = jQuery(el);
$el.queue(next => {
el.addEventListener(transitionEnd, function() {
if (callback) {
callback($el);
}
next();
}, false);
});
});
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment