|
| 1 | +# Prevent Hidden Element From Flickering On Load |
| 2 | + |
| 3 | +Here is what it might look like to use [Alpine.js](https://alpinejs.dev/) to |
| 4 | +sprinkle in some JavaScript for controlling a dropdown menu. |
| 5 | + |
| 6 | +```html |
| 7 | +<div x-data="{ profileDropdownOpen: false }"> |
| 8 | + <button |
| 9 | + type="button" |
| 10 | + @click="profileDropdownOpen = !profileDropdownOpen" |
| 11 | + > |
| 12 | + <!-- some inner html --> |
| 13 | + </button> |
| 14 | + <div x-show="profileDropdownOpen" role="menu"> |
| 15 | + <a href="/profile" role="menuitem">Your Profile</a> |
| 16 | + <a href="/sign-out" role="menuitem">Sign Out</a> |
| 17 | + </div> |
| 18 | +</div> |
| 19 | +``` |
| 20 | + |
| 21 | +Functionally that will work. You can click the button to toggle the menu open |
| 22 | +and closed. |
| 23 | + |
| 24 | +What you might notice, however, when you refresh the page is that the menu |
| 25 | +flickers open as the page first loads and then disappears. This is a quirk of |
| 26 | +the element being rendered before Alpine.js is loaded and the |
| 27 | +[`x-show`](https://alpinejs.dev/directives/show) directive has a chance to take |
| 28 | +effect. |
| 29 | + |
| 30 | +To get around this, we can _cloak_ any element with an `x-show` directive that |
| 31 | +should be hidden by default. |
| 32 | + |
| 33 | +```html |
| 34 | +<div x-data="{ profileDropdownOpen: false }"> |
| 35 | + <button |
| 36 | + type="button" |
| 37 | + @click="profileDropdownOpen = !profileDropdownOpen" |
| 38 | + > |
| 39 | + <!-- some inner html --> |
| 40 | + </button> |
| 41 | + <div x-cloak x-show="profileDropdownOpen" role="menu"> |
| 42 | + <a href="/profile" role="menuitem">Your Profile</a> |
| 43 | + <a href="/sign-out" role="menuitem">Sign Out</a> |
| 44 | + </div> |
| 45 | +</div> |
| 46 | +``` |
| 47 | + |
| 48 | +This addition needs to be paired with some custom CSS to hide any _cloaked_ |
| 49 | +elements. |
| 50 | + |
| 51 | +```css |
| 52 | +[x-cloak] { display: none !important; } |
| 53 | +``` |
| 54 | + |
| 55 | +[source](https://alpinejs.dev/directives/cloak) |
0 commit comments