Skip to content

Instantly share code, notes, and snippets.

@freekrai
Forked from AceCodePt/hx-astro-view-transition.js
Last active September 29, 2024 16:02
Show Gist options
  • Save freekrai/286f0f0afb5cb638fc70fd6d9fd38cf9 to your computer and use it in GitHub Desktop.
Save freekrai/286f0f0afb5cb638fc70fd6d9fd38cf9 to your computer and use it in GitHub Desktop.
htmx-astro-view-transition

Add it to the body

<body hx-ext="hx-astro-view-transition">

An example

<form
        hx-post="/api/signIn"
        hx-view-transition="/"
        hx-swap="none"
      >

Note: if you are using SSR

You might want to add the following in the layout.astro:

Astro.response.headers.set(
  "Cache-Control",
  "no-cache, no-store, must-revalidate",
);
Astro.response.headers.set("Pragma", "no-cache");
Astro.response.headers.set("Expires", "0");
htmx.defineExtension("hx-astro-view-transition", {
onEvent: function (name, evt: any) {
if (name === "htmx:afterRequest") {
const attributes = evt.target.attributes;
const viewTransitionTarget =
attributes["hx-view-transition"]?.value;
if (!viewTransitionTarget) {
console.log(evt);
return;
}
const a = document.createElement("a");
a.href = viewTransitionTarget;
console.count(viewTransitionTarget);
document.body.appendChild(a);
a.dispatchEvent(
new PointerEvent("mouseenter", {
bubbles: true,
cancelable: true,
}),
);
a.dispatchEvent(
new PointerEvent("click", {
bubbles: true,
cancelable: true,
}),
);
}
},
});
// Runs on view transitions navigation + process the new HTML
document.addEventListener("astro:after-swap", () =>
htmx.process(document),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment