#does onclick work with .astro
2 messages · Page 1 of 1 (latest)
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).