#does onclick work with .astro

2 messages · Page 1 of 1 (latest)

neat timberBOT
#

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

#

Astro does not directly support onclick attributes or custom event handling syntax like some UI frameworks do. Instead, Astro follows standard HTML more closely for handling events in .astro files.

To handle click events in an Astro component, you should use the standard addEventListener method within a <script> tag. Here's an example of how you can handle a click event in an Astro component:

<button class="alert">Click me!</button>

<script>
  // Find all buttons with the `alert` class on the page.
  const buttons = document.querySelectorAll('button.alert');

  // Handle clicks on each button.
  buttons.forEach((button) => {
    button.addEventListener('click', () => {
      alert('Button was clicked!');
    });
  });
</script>

This approach allows you to add interactivity to your Astro components using vanilla JavaScript, without requiring any additional UI framework Common script patterns (https://docs.astro.build/en/guides/client-side-scripts/#common-script-patterns).

Remember that scripts in Astro components are processed and bundled by default, allowing you to use imports and TypeScript. The script will only be included once per page, even if the component is used multiple times Scripts and Event Handling (https://docs.astro.build/en/guides/client-side-scripts/#using-script-in-astro).

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