Created
September 13, 2022 15:49
-
-
Save jaredcwhite/ee217f701f67f0cc2bc80683c933174c to your computer and use it in GitHub Desktop.
Nice transitions using Turbo
This file contains hidden or 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
document.addEventListener("turbo:visit", () => { | |
let main = document.querySelector("main"); | |
if (main.dataset.turboTransition == "false") return; | |
let [movement, scale] = ["-12px", "0.99"]; | |
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { | |
[movement, scale] = ["-6px", "1"] | |
}; | |
main.style.transformOrigin = "0% 0%"; | |
main.dataset.animatingOut = true; | |
main.animate( | |
[ | |
{ opacity: 1, transform: "translateX(0px) scale(1)" }, | |
{ opacity: 0, transform: `translateX(${movement}) scale(${scale})` } | |
], | |
{ duration: 200, easing: "cubic-bezier(0.45, 0, 0.55, 1)", fill: "forwards" } | |
); | |
Promise.all(main.getAnimations().map(animation => animation.finished)).then(() => { | |
if (main.dataset.animatingOut) main.style.visibility = "hidden" | |
}) | |
}); | |
document.addEventListener("turbo:load", () => { | |
let main = document.querySelector("main"); | |
if (main.dataset.turboTransition == "false") return; | |
if (window.bypassTurboTransition) { | |
window.bypassTurboTransition = false | |
return | |
} | |
let [movement, scale] = ["-10px", "0.99"]; | |
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { | |
[movement, scale] = ["-5px", "1"] | |
}; | |
main.style.visibility = "visible"; | |
main.style.transformOrigin = "0% 0%"; | |
delete main.dataset.animatingOut; | |
main.animate( | |
[ | |
{ opacity: 0, transform: `translateX(${movement}) scale(${scale})` }, | |
{ opacity: 1, transform: "translateX(0px) scale(1)" } | |
], | |
{ duration: 200, easing: "cubic-bezier(0.45, 0, 0.55, 1)" } | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment