#PathChange fires a function

3 messages · Page 1 of 1 (latest)

visual sequoia
#

I'm trying to make a function run when the path changes. I've searched quite a bit and haven't found anything. The astro:after-swap eventListener doesn't work for me because viewTransitions are not supported in Safari or Mozilla, and it wouldn't work in these browsers.

hasty crestBOT
#

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

#

Astro provides two events during client-side routing that you can listen for: astro:page-load and astro:after-swap. However, as you mentioned, the astro:after-swap event might not work in browsers where ViewTransitions are not supported, such as Safari and Mozilla.

In such cases, you can use the astro:page-load event, which fires at the end of page navigation, after the new page is visible to the user and blocking styles and scripts are loaded. This event is fired both on initial page navigation (MPA) and any subsequent navigation, either forwards or backwards.

Here's an example of how you can use this event to run a function when the path changes:

document.addEventListener('astro:page-load', () => {
  // Your function here
});

This will ensure that your function runs every time a new page is loaded, which should effectively mean it runs when the path changes.

For more information, you can refer to the Astro documentation on View Transitions (https://docs.astro.build/en/guides/view-transitions/).

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