-3

why js file not working in Astro when I import or add src in Astro file? ex: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script>

I'm working on a local environment and I'm sure I've written my src URl correctly but my functions aren't working. this is my written js code

const navLinks = document.querySelectorAll("[data-navLink]");
navLinks.forEach((link) => {
  if (link.getAttribute("href") === window.location.pathname) {
    link.setAttribute("aria-current", "page");
    console.log(window.location.pathname);
  }
});
j0k
  • 22,600
  • 28
  • 79
  • 90
  • you can only `import` in a `module` ` – Jaromanda X Mar 17 '23 at 05:23

1 Answers1

1

<script> tags are hoisted as type="module" by default, for your script you need to add a is:inline directive to opt out of this default and inline your script

This section of this docs: Scripts and Event Handling, has a bunch of great information on how client side scripts work in Astro

It is also worth noting that you can create active links server side using Astro.url.pathname instead of using a client-side script

<a aria-current={Astro.url.pathname === '/home' ? 'page' : null}>Home</a>
Bryce Russell
  • 647
  • 3
  • 8