#Button as Component

4 messages · Page 1 of 1 (latest)

vale mason
#

Hey, currently I have a sitewide button component. How can I run code when this component is clicked upon and how can I differentiate the buttons for the code?

prime summitBOT
#

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

#

In Astro, you can add interactivity to your components using standard HTML <script> tags. This allows you to send JavaScript to run in the browser and add functionality to your components.

To run code when a button is clicked, you can use the addEventListener method in a <script> tag to handle user interactions. Here's an example:

<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>

In this example, the querySelectorAll method is used to select all buttons with the alert class. An event listener is then added to each button to handle click events.

To differentiate the buttons for the code, you can use different classes or data-* attributes for each button. For example, you can use data-* attributes to store the value of variables in your HTML output. Scripts, including custom elements, can then read these attributes using an element’s dataset property once your HTML loads in the browser.

Here's an example of how you can use data-* attributes:

<button data-confetti-button>Celebrate!</button>
<script>
  // Import npm modules.
  import confetti from 'canvas-confetti';

  // Find our component DOM on the page.
  const buttons = document.querySelectorAll('[data-confetti-button]');
#

// Add event listeners to fire confetti when a button is clicked.
buttons.forEach((button) => {
button.addEventListener('click', () => confetti());
});
</script>

In this example, the `querySelectorAll` method is used to select all buttons with the `data-confetti-button` attribute. An event listener is then added to each button to handle click events and fire confetti.

For more information, you can refer to the **Astro documentation on Scripts and Event Handling** (<https://docs.astro.build/en/guides/client-side-scripts/#_top>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------