#document.addEventListener("astro:page-load", () => {
2 messages · Page 1 of 1 (latest)
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:
- 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.
- Alternatively, you can use the
onceoption 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.