Interactivity and Event Handling
Learn how to make the components interactive and how to work with scripts and event handlers.
Handling user events—such as clicking elements—is a crucial part of adding interactivity to web pages. It helps us execute code when a user action takes place to make a page interactive. This can include many things from toggling the visibility of elements to more complex examples, such as sending email directly from a web page. In this lesson, we’ll take a look at how to integrate client-side JavaScript code into Astro components to add interactivity to elements.
Integrating scripts
To make Astro components interactive, we need to write JavaScript-related code between the script
tags. Inside the script
tags, we’re free to use imports, as well as TypeScript. By default, Astro will bundle and minify any JavaScript code found in components. It also ensures that if the component is used multiple times, the script will still be included only once.
<script>document.querySelector('h1').addEventListener('click', () => {alert('Hello from script! đź‘‹');});</script>
To try out how the script
tag works in Astro, add the code given above into the code widget below inside src/pages/index.astro
and click h1
.
Inline scripts
We can also avoid bundling, in case we need to, with the use of the is:inline
directive. This should only be used when we need the script to be present in the HTML as is.
<script is:inline>// - Will be rendered as is// - No imports available// - Included each time a component is used</script><!-- Use it for 3rd party scripts --><script is:inline src="https://example.com/lib.js" />
Because script tags with the is:inline
directives will not be bundled, it’s also worth mentioning that we won’t be able to use imports inside these script tags.
As a side effect, the script will be included each time the component is used. ...