br7
br7

Reputation: 21

Astro component script only run once

I have an Astro component with a script for control scroll animations. The problem is the following. When the index is loaded, the script is executed and the animation is activated without problem. But when I change the page and return to the index the code no longer runs again. Any idea how I could fix it?

   const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
         if (entry.isIntersecting) {
            entry.target.classList.add("move");
         }
      });
   });

   const icons = document.querySelectorAll(".service-icon");
   icons.forEach((icon) => observer.observe(icon));

Upvotes: 2

Views: 1761

Answers (3)

jessmzn
jessmzn

Reputation: 122

To ensure that a script runs every time a page is loaded during client-side navigation, it should be executed by a lifecycle event. For example, event listeners for DOMContentLoaded can be replaced by the astro:page-load lifecycle event.

docs view-transitions

I changed document.addEventListener("DOMContentLoaded", () => { To document.addEventListener("astro:page-load", () => {

Everything working fine.

Upvotes: 0

Angelo M
Angelo M

Reputation: 1

I had the same problem then I read the documentation and I found that Astro has the possibility to create custom elements. By default, astro run just once the scripts in your project, but using custom elements allows the browser to run your element everytime it's found.
Here is an example:

<astro-element>
<button>Counter:</button> <span>0</span>
</astro-element>

<script>
class AstroElement extends HTMLElement {
  constructor() {
    super();
    let count = 0;

    const countButton = this.querySelector('button');
    const countSpan = this.querySelector('span');

    countButton.addEventListener('click', () => {
      count++;
      countSpan.textContent = count.toString();
    });
  }
}
customElements.define('astro-element', AstroElement);
</script>

This will allows you to run it multiple times.
For more information, here it is a link to the documentation:
https://docs.astro.build/en/guides/client-side-scripts/#web-components-with-custom-elements
Search for the Web components with custom elements section.

Upvotes: 0

Alex
Alex

Reputation: 353

(For clarity) you can use lifecycle events when using View Transitions - this is because you need to re-run any scripts/code after navigating to another page.

Upvotes: 0

Related Questions