Toggles and Dropdowns
index.html
To create interactive toggles and dropdown menus with Alpine.js, you combine several core directives to manage state and user interaction. The example above uses x-data to define state, specifically an open property that tracks whether the dropdown is visible. When you click the button, the x-on:click directive toggles the open state. The dropdown menu itself uses x-show to only display when open is true, and x-transition provides a simple animation effect.
Accessibility is enhanced by using ARIA attributes. The button uses aria-haspopup="true" to indicate it controls a menu, and :aria-expanded="open" to reflect the open state. The dropdown menu uses role="menu" and its items have role="menuitem" with tabindex="0" for keyboard navigation. The @click.away directive automatically closes the menu if you click outside of it, mimicking native dropdown behavior and improving usability. This combination of Alpine.js directives and semantic HTML ensures that your toggles and dropdowns are both interactive and accessible.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Fantastisk!
Completion rate forbedret til 6.67
Toggles and Dropdowns
Stryg for at vise menuen
index.html
To create interactive toggles and dropdown menus with Alpine.js, you combine several core directives to manage state and user interaction. The example above uses x-data to define state, specifically an open property that tracks whether the dropdown is visible. When you click the button, the x-on:click directive toggles the open state. The dropdown menu itself uses x-show to only display when open is true, and x-transition provides a simple animation effect.
Accessibility is enhanced by using ARIA attributes. The button uses aria-haspopup="true" to indicate it controls a menu, and :aria-expanded="open" to reflect the open state. The dropdown menu uses role="menu" and its items have role="menuitem" with tabindex="0" for keyboard navigation. The @click.away directive automatically closes the menu if you click outside of it, mimicking native dropdown behavior and improving usability. This combination of Alpine.js directives and semantic HTML ensures that your toggles and dropdowns are both interactive and accessible.
Tak for dine kommentarer!