Skip to content

Instantly share code, notes, and snippets.

@jamesbirtles
Created April 15, 2016 23:41
Show Gist options
  • Save jamesbirtles/f54919d53b326b57149b50528e76d31c to your computer and use it in GitHub Desktop.
Save jamesbirtles/f54919d53b326b57149b50528e76d31c to your computer and use it in GitHub Desktop.
Transition between two elements in angular 2, works well with text.
function transitionTo(parent: any, from: any, to: any): Promise<void> {
return new Promise<void>(resolve => {
const transitionElement = DOM.clone(from);
const fromBCR: ClientRect = DOM.getBoundingClientRect(from);
// Hide old element until animation is complete.
DOM.setStyle(from, "display", "none");
// Temporarily display to element to get the BCR and styles.
DOM.setStyle(to, "display", "block");
const toBCR = DOM.getBoundingClientRect(to);
const toStyles = DOM.getComputedStyle(to);
DOM.setStyle(to, "display", "none");
// Setup transition element
DOM.setStyle(transitionElement, "transition", "0.6s all");
DOM.setStyle(transitionElement, "position", "absolute");
DOM.setStyle(transitionElement, "top", fromBCR.top + "px");
DOM.setStyle(transitionElement, "left", fromBCR.left + "px");
DOM.setStyle(transitionElement, "width", fromBCR.width + "px");
DOM.setStyle(transitionElement, "height", fromBCR.height + "px");
// Add transition element to the parent.
DOM.appendChild(parent, transitionElement);
// Wait one frame for all the styles to take effect.
DOM.requestAnimationFrame(() => {
DOM.setStyle(transitionElement, "top", toBCR.top + "px");
DOM.setStyle(transitionElement, "left", toBCR.left + "px");
DOM.setStyle(transitionElement, "width", toBCR.width + "px");
DOM.setStyle(transitionElement, "height", toBCR.height + "px");
DOM.setStyle(transitionElement, "font-size", toStyles["font-size"]);
const onTransitionEnd = () => {
DOM.remove(transitionElement);
DOM.removeStyle(to, "display");
transitionElement.removeEventListener("transitionend", onTransitionEnd);
resolve(null);
};
transitionElement.addEventListener("transitionend", onTransitionEnd);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment