#document.addEventListener("astro:page-load", () => {

2 messages · Page 1 of 1 (latest)

hoary viperBOT
#

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

#

To address your issue with multiple event listeners being attached to your form during navigation between routes when using Astro's view transitions, you can use the following approach:

  1. Remove old event listeners before adding new ones:
document.addEventListener("astro:page-load", () => {
  // Remove old event listeners
  document.removeEventListener("submit", handleSubmit);
  
  // Add new event listener
  document.addEventListener("submit", handleSubmit);
});

function handleSubmit(event) {
  // Your form submission logic here
}

This approach ensures that you remove the old event listener before adding a new one on each page load.

  1. Alternatively, you can use the once option when adding the event listener:
document.addEventListener("astro:page-load", () => {
  document.addEventListener("submit", handleSubmit, { once: true });
});

function handleSubmit(event) {
  // Your form submission logic here
}

The { once: true } option automatically removes the event listener after it's triggered once, preventing multiple listeners from accumulating.

These solutions should help prevent the accumulation of multiple event listeners on your form as you navigate between different routes using Astro's view transitions.

For more information on the astro:page-load event and script behavior with view transitions, you can refer to the Astro documentation on View Transitions.

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