#How do i activate a click function on a anchor tag?

3 messages · Page 1 of 1 (latest)

tribal flint
#

can astro support onCLick on a <a> element?

hollow capeBOT
#

Hi @tribal flint. 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 support using JSX-style event handlers like onClick={...} directly on HTML elements such as <a> tags in your .astro files. Instead, Astro follows standard HTML and recommends adding interactivity using JavaScript in a <script> tag.

To activate a click function on an anchor (<a>) tag, you should use addEventListener inside a <script> tag. Here’s an example:

<a id="my-link" href="#">Click me!</a>
<script>
  document.getElementById('my-link').addEventListener('click', (event) => {
    event.preventDefault(); // Prevents the default link behavior
    alert('Anchor was clicked!');
  });
</script>

This approach is the recommended way in Astro to handle events like clicks on elements, since Astro does not process custom event handler attributes like onClick (as in React or Vue). You must use standard DOM event listeners in your scripts instead. For more details, see the Astro documentation on scripts and event handling and the template expressions reference.

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