Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

x-show and x-transition

The x-show directive shows an element when an expression is true and hides it when it is false. The element stays in the markup — Alpine only toggles display: none on it. The x-transition directive adds a smooth fade in and out.

x-show

A hint in the to-do list that can be hidden:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{ open: true }">
  <button @click="open = !open">Hint</button>
  <p x-show="open">Press Enter to add a task.</p>
</div>

The button hides the paragraph and shows it again. The expression open = !open flips the value.

A condition from data

x-show takes any expression, for example a check of an array's length:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{ tasks: [] }">
  <button @click="tasks.push('Task')">Add</button>
  <button @click="tasks = []">Clear</button>
  <p x-show="tasks.length === 0">The list is empty.</p>
  <p x-show="tasks.length > 0" x-text="'Tasks: ' + tasks.length"></p>
</div>

While there are no tasks you see "The list is empty.". After the first one is added, a counter replaces it.

x-transition

Adding x-transition with no value is enough — the element fades and slightly scales in:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{ open: false }">
  <button @click="open = !open">Details</button>
  <p x-show="open" x-transition>Task created by Anna on May 3.</p>
</div>

The paragraph appears and disappears smoothly, in about 150 ms.

Tuning the transition

Modifiers change the animation:

SyntaxWhat it does
x-transition.duration.500ms500 ms duration
x-transition.opacityFade only, no scale
x-transition.scale.90Scale from 90%, no fade

For full control, transitions are set with CSS classes for each stage — handy with Tailwind:

<div
  x-show="open"
  x-transition:enter="transition ease-out duration-300"
  x-transition:enter-start="opacity-0"
  x-transition:enter-end="opacity-100"
  x-transition:leave="transition ease-in duration-200"
  x-transition:leave-start="opacity-100"
  x-transition:leave-end="opacity-0"
>
  ...
</div>

The enter and leave stages describe appearing and disappearing, -start and -end the state at the beginning and the end.

Common mistake

Putting x-show on an element whose CSS sets display with !important. Alpine hides the element with an inline display: none style, and the !important rule overrides it — the element never hides. Remove !important from the CSS or add a modifier to the directive: x-show.important="open".

Thanks for reading!

Donate to the site — we work hard for you.