#client:only without a framework

1 messages · Page 1 of 1 (latest)

grim mulch
#

I want to render a button that calls plain JS, window.print()

How can I load this button in the browser only, without using a framework?

shut parrotBOT
#

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

#

You can achieve this by using a <script> tag in your Astro component to send JavaScript to the browser that executes in the global scope. This way, you can add interactivity without needing to know or learn any other JavaScript frameworks.

Here's an example of how you can do this:

<button id="printButton">Print</button>

<script>
  const printButton = document.querySelector('#printButton');
  printButton.addEventListener('click', () => {
    window.print();
  });
</script>

In this example, we're creating a button with an id of printButton. Then, we're using a <script> tag to add an event listener to the button. When the button is clicked, it will call window.print() to print the page.

Please note that Astro components are HTML-only templating components with no client-side runtime. If you try to hydrate an Astro component with a client: modifier, you will get an error. The client: directives are used for hydrating UI Framework components, not Astro components.

For more information, you can refer to the Astro documentation on client-side scripts (https://docs.astro.build/en/guides/client-side-scripts/) and Astro components (https://docs.astro.build/en/basics/astro-components/).

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