Alpine sticky header

Simple demo to show an element with with Alpine.js

by James Doyle

HTML

<script src="https://cdn.jsdelivr.net/npm/@alpinejs/[email protected]/dist/cdn.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
<div class="min-h-20 bg-green-50"></div>
<!-- this element will trigger the state -->
<div
  x-data
  x-intersect:enter.full="$dispatch('unlock')"
  x-intersect:leave.full="$dispatch('lock')"
></div>
<!-- this is the actual element that is affected -->
<div
  class="sticky top-0 z-20"
  x-cloak
  x-data="{ isLocked: false }"
  x-on:unlock.window="isLocked = false"
  x-on:lock.window="isLocked = true"
>
  <div
    class="w-full bg-white"
    :class="{ 'drop-shadow-md bg-red-300': isLocked }"
  >
    <div>Sticky Header Content (Turns red when fixed)</div>
  </div>
</div>
<div class="min-h-screen bg-yellow-50"></div>
<div class="min-h-screen bg-blue-50"></div>

Tailwind CSS

[x-cloak],
[x-cloak]>* {
  display: none;
}

[x-cloak]::before {
  content: "loading\2026";
}