DEV Community

loading...

Discussion on: Alpine.js: responsive x-cloak

hus_hmd profile image
Hussein Al Hammad Author

Sure thing. Perhaps the post was light on the possible use-cases for this.

Firstly to recap, x-cloak is an attribute that Alpine.js removes from HTML elements once it is initialised. So you have the following phases:

  1. HTML is rendered in the browser, Alpine.js is yet to initialise. HTML elements still have the x-cloak attribute.
  2. Alpine.js is initialised. Alpine.js removes the x-cloak attribute from HTML elements.

So during (1), [x-cloak=""] styles are applied. During (2), they are no longer applied to the elements because the elements no longer have the x-cloak attribute.

A user with a slow internet connection for instance may view a page in phase (1) for some time. During this time you may not want to hide some elements by default.

Taking the dropdown example from Alpine's docs:

<div x-data="{ open: false }">
    <button @click="open = true">Open Dropdown</button>

    <ul
        x-show="open"
        @click.away="open = false"
    >
        Dropdown Body
        <!-- this ul is visible during phase (1) -->
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

If we apply x-cloak to the <ul>, we can hide it during phase (1):

<div x-data="{ open: false }">
    <button @click="open = true">Open Dropdown</button>

    <ul
        x-cloak
        x-show="open"
        @click.away="open = false"
    >
        Dropdown Body
        <!-- this ul is NOT visible during phase (1) -->
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

In the example of a dropdown, such a component typically behaves in an identical way across different screen sizes.

However, for some components you may want to have some elements hidden during phase (1) only on some screen sizes. A common example is the main navigation bar of a website where you have the links displayed by default on larger screens, but want to have them hidden on smaller screens. In other words, the initial state for the element is not identical across screen sizes. This is where [x-cloak="mobile"] can be useful.

Note that this is useful if you are toggling display with Alpine (e.g. with x-show):

<div x-show="open" x-cloak="mobile"></div>
Enter fullscreen mode Exit fullscreen mode

If you are using Alpine to toggle CSS classes you may not need this as your CSS may already handle this:

<style>
    @media screen and (max-width: 768px) {
        .example:not(.active) {
            display: none;
        }
    }
</style>

<div class="example" :class="{'active': open}"></div>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
makingthings profile image
James Grubb

Hi Hussein, I realised I did not get to thank you for your follow up post. I really appreciate your time and I am very grateful. Cheers, James.