#after swap

7 messages · Page 1 of 1 (latest)

celest plover
#

how do i configure something to run with the astro:after-swap event?

smoky bluffBOT
#

Hi @celest plover. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To run code in response to the astro:after-swap event, add an event listener to the document for "astro:after-swap". This event fires immediately after the new page replaces the old page during client-side navigation with Astro’s View Transitions. You can use this to trigger actions before the new page’s DOM elements render and scripts run.

Here’s an example:

document.addEventListener("astro:after-swap", () => {
  // Your code here, e.g., reset scroll position
  window.scrollTo({ left: 0, top: 0, behavior: "instant" });
});

You can place this script in your page or component. This is useful for tasks like restoring scroll position, updating themes, or transferring state between navigations View transitions: astro:after-swap.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@celest plover Kapa.ai is still learning and improving, please let me know how I did by reacting below.

celest plover
#

@smoky bluff i need to run MOS.refreshHard with the astro:after-swap event. What's the correct syntax?

smoky bluffBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

To run MOS.refreshHard with the astro:after-swap event, you should add an event listener to the document for "astro:after-swap" and call your function inside the handler. The correct syntax, based on the official Astro documentation, is:

document.addEventListener("astro:after-swap", () => {
  MOS.refreshHard();
});

Place this script in your page or component where it will be executed on every client-side navigation after the swap phase, before the new DOM is rendered and scripts run View transitions: astro:after-swap.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: