1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Prevent Hidden Element From Flickering On Load as a JavaScript TIL

This commit is contained in:
jbranchaud
2024-10-30 15:11:41 -05:00
parent 21385f4491
commit 63bb627716
2 changed files with 57 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1490 TILs and counting..._
_1491 TILs and counting..._
---
@@ -524,6 +524,7 @@ _1490 TILs and counting..._
- [Open Global npm Config File](javascript/open-global-npm-config-file.md)
- [Parse A Date From A Timestamp](javascript/parse-a-date-from-a-timestamp.md)
- [Pre And Post Hooks For Yarn Scripts](javascript/pre-and-post-hooks-for-yarn-scripts.md)
- [Prevent Hidden Element From Flickering On Load](javascript/prevent-hidden-element-from-flickering-on-load.md)
- [Purge Null And Undefined Values From Object](javascript/purge-null-and-undefined-values-from-object.md)
- [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md)
- [Reach Into An Object For Nested Data With Get](javascript/reach-into-an-object-for-nested-data-with-get.md)

View File

@@ -0,0 +1,55 @@
# Prevent Hidden Element From Flickering On Load
Here is what it might look like to use [Alpine.js](https://alpinejs.dev/) to
sprinkle in some JavaScript for controlling a dropdown menu.
```html
<div x-data="{ profileDropdownOpen: false }">
<button
type="button"
@click="profileDropdownOpen = !profileDropdownOpen"
>
<!-- some inner html -->
</button>
<div x-show="profileDropdownOpen" role="menu">
<a href="/profile" role="menuitem">Your Profile</a>
<a href="/sign-out" role="menuitem">Sign Out</a>
</div>
</div>
```
Functionally that will work. You can click the button to toggle the menu open
and closed.
What you might notice, however, when you refresh the page is that the menu
flickers open as the page first loads and then disappears. This is a quirk of
the element being rendered before Alpine.js is loaded and the
[`x-show`](https://alpinejs.dev/directives/show) directive has a chance to take
effect.
To get around this, we can _cloak_ any element with an `x-show` directive that
should be hidden by default.
```html
<div x-data="{ profileDropdownOpen: false }">
<button
type="button"
@click="profileDropdownOpen = !profileDropdownOpen"
>
<!-- some inner html -->
</button>
<div x-cloak x-show="profileDropdownOpen" role="menu">
<a href="/profile" role="menuitem">Your Profile</a>
<a href="/sign-out" role="menuitem">Sign Out</a>
</div>
</div>
```
This addition needs to be paired with some custom CSS to hide any _cloaked_
elements.
```css
[x-cloak] { display: none !important; }
```
[source](https://alpinejs.dev/directives/cloak)