Astro
Send your first script to the browser
Send your first script to the browser
Let's add a button to open and close your navigation menu on mobile screen sizes, requiring some client-side interactivity!
- Create a menu component
- Write a
<script>to allow your site visitors to open and close the navigation menu - Move your JavaScript to its
.jsfile
Build a Menu component
Create a <Menu /> component to open and close your mobile menu.
Copy the following code into your component. It creates a button that will be used to toggle the visibility of the navigation links on mobile devices. (You will add the new CSS styles to
global.csslater.)--- --- <button aria-expanded="false" aria-controls="main-menu" class="menu"> Menu </button>Place this new
<Menu />component just before your<Navigation />component inHeader.astro.Show me the code!
--- import Menu from './Menu.astro'; import Navigation from './Navigation.astro'; --- <header> <nav> <Menu /> <Navigation /> </nav> </header>Add the following styles for your Menu component, including some responsive styles:
/* nav styles */ .menu { background-color: #0d0950; border: none; color: #fff; font-size: 1.2rem; font-weight: bold; padding: 5px 10px; } .nav-links { width: 100%; display: none; margin: 0; } .nav-links a { display: block; text-align: center; padding: 10px 0; text-decoration: none; font-size: 1.2rem; font-weight: bold; text-transform: uppercase; color: #0d0950; } .nav-links a:hover, .nav-links a:focus{ background-color: #ff9776; } :has(.menu[aria-expanded="true"]) .nav-links { display: unset; } @media screen and (min-width: 636px) { .nav-links { margin-left: 5em; display: block; position: static; width: auto; background: none; } .nav-links a { display: inline-block; padding: 15px 20px; } .menu { display: none; } }
Write your first script tag
Your header is not yet interactive because it can't respond to user input, like clicking on the menu to show or hide the navigation links.
Adding a <script> tag provides client-side JavaScript to "listen" for a user event and then respond accordingly.