#script tag inside array map

1 messages · Page 1 of 1 (latest)

glad maple
#

Is it possible to define a script for each element of an array inside a map? I need to do this because I define variables for each element into the script like this:

{modes.map((mode) => {
  <script define:vars={{ name: mode.name, path: mode.link }}>
    function updateModeLinksWithHash() {
      const links = document.querySelectorAll(
        `.starlight-view-modes-switcher-a-${name}`
      );
      if (links.length > 0) {
        const hash = window.location.hash;
        links.forEach((link) => {
          link.href = path + hash;
        });
      }
    }

    // Run on initial load
    updateModeLinksWithHash();

    // Update on hash change
    window.addEventListener("hashchange", updateModeLinksWithHash);
  </script>
})}
glad maple
#

Solved in a different way:

<script>
  function updateModeLinksWithHash() {
    const hash = window.location.hash;
    document
      .querySelectorAll(".starlight-view-modes-switcher-a")
      .forEach((link) => {
        // @ts-ignore
        if (link.href) {
          // @ts-ignore
          link.href = link.href.split("#")[0] + hash;
        }
      });
  }

  // Run on initial load
  updateModeLinksWithHash();

  // Update on hash change
  window.addEventListener("hashchange", updateModeLinksWithHash);
</script>