Created
August 12, 2025 10:35
-
-
Save GrimLink/a7bfd9152cfb81d32cc8e2a183ff09ef to your computer and use it in GitHub Desktop.
AlpineJS BFCache example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <script src="//unpkg.com/alpinejs" defer></script> | |
| <div x-data="menuExample" x-bind="eventListeners"> | |
| <button @click="toggle">Expand</button> | |
| <div x-show="open"> | |
| Menu Content... | |
| </div> | |
| </div> | |
| <script> | |
| document.addEventListener('alpine:init', () => { | |
| Alpine.data('menuExample', () => ({ | |
| open: false, | |
| toggle() { | |
| this.open = !this.open | |
| }, | |
| eventListeners: { | |
| ['@pageshow.window'](event) { | |
| if (event.persisted) { | |
| this.open = false | |
| }; | |
| } | |
| } | |
| })) | |
| }) | |
| </script> |
Author
I disagree, the state is handled by open value.
The action to close the menu is the correct way, while it should not be possible, the toggle can open the menu, which could cause unwanted side effects.
This give you an example the aria roles can be set using just the open state.
<div x-data="menuExample" x-bind="eventListeners">
<button
@click="toggle"
:aria-expanded="open"
>Expand</button>
<div x-show="open">
Menu Content...
</div>
</div>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would probably change the if statement within
@pageshow.windowto:All possible future accessibility handling (such as
aria-expandedonmenuExample) will probably also happen intoggle(). Meaning that callingtoggle()directly prevents the need for double work.