---
title: "Alpine.js Dialog Pattern"
description: "Build focus-trapped modal dialogs with huxDialog for Alpine.js with scoped lifecycle events."
url: "https://js.hyperui.dev/patterns/dialog"
---

# Alpine.js Dialog Pattern

Build focus-trapped modal dialogs with huxDialog for Alpine.js with scoped lifecycle events.

- Registrations: `huxDialog`
- Keywords: dialog, modal, alpinejs, focus-trap, accessibility, overlay, slide-over, drawer, panel
- Updated: 2026-11-23

## Setup

Registrations needed: `huxDialog`. Each one listens for `alpine:init`, so it must load before Alpine starts.

- Script tags: add each registration as a plain `<script>` placed before the Alpine script.
- Bundlers: set `window.Alpine = Alpine`, import the registration files, then call `Alpine.start()`. The registrations reference the global `Alpine`.
- No CSS is included. Add `[x-cloak] { display: none !important; }` and your own `:focus-visible` style if your project has none.

`huxDialog` handles open/close state, optional backdrop behavior, and scoped lifecycle events for modal UI in Alpine.js. Pair it with your own dialog markup and focus trap directives.

This pattern expects the Alpine Focus plugin when you use `x-trap` in your markup: [@alpinejs/focus](https://cdn.jsdelivr.net/npm/@alpinejs/focus@3.15/dist/cdn.min.js).

## API

### `huxDialog(config)`

Returns an Alpine data object with:

- `isOpen: boolean`
- `dialogId: string | null`
- `isPersistent: boolean`
- `isSeamless: boolean`
- `returnFocusOnClose: boolean`
- `dialogTitleId: string | null`
- `dialogDescriptionId: string | null`
- `closeOnBackdrop: boolean`
- `closeOnEscape: boolean`
- `showBackdrop: boolean`
- `openDialog(): void`
- `toggleDialog(): void`
- `closeDialog(): void`
- `handleBackdropClick(): void`
- `handleEscape(): void`

_Internal helper methods are private implementation details and are not part of the supported API contract._

## Options

- `dialogId: string` (optional)
- `startsOpen: boolean` (default: `false`)
- `isPersistent: boolean` (default: `false`)
- `isSeamless: boolean` (default: `false`)
- `returnFocusOnClose: boolean` (default: `true`)

## Quick Start

```html
<div x-data="huxDialog({ dialogId: 'settings' })">
  <button type="button" x-on:click="openDialog()">Open dialog</button>

  <template x-teleport="body">
    <div x-cloak x-show="isOpen" x-on:keydown.escape.stop="handleEscape()">
      <div
        x-cloak
        x-show="showBackdrop"
        aria-hidden="true"
        x-on:click="handleBackdropClick()"
      ></div>

      <div
        x-trap.noscroll="isOpen"
        role="dialog"
        aria-modal="true"
        x-bind:aria-labelledby="dialogTitleId || null"
        x-bind:aria-describedby="dialogDescriptionId || null"
      >
        <h2 x-bind:id="dialogTitleId || null">Settings</h2>
        <p x-bind:id="dialogDescriptionId || null">Update your account preferences.</p>
        <button type="button" x-on:click="closeDialog()">Close</button>
      </div>
    </div>
  </template>
</div>
```

## Common Usage Patterns

### Persistent Confirmation Dialog

```js
huxDialog({
  dialogId: 'confirm-delete',
  isPersistent: true,
})
```

### Seamless Dialog (No Backdrop)

```js
huxDialog({
  dialogId: 'quick-actions',
  isSeamless: true,
})
```

### Slide-over Panel

`huxDialog` can drive a slide-over panel — a full-height drawer that slides in from a screen edge. No additional component is needed; the slide animation and positioning are handled entirely with CSS transition classes.

```html
<div x-data="huxDialog({ dialogId: 'settings' })">
  <button type="button" x-on:click="openDialog()">Open</button>

  <template x-teleport="body">
    <div
      x-cloak
      x-show="isOpen"
      class="fixed inset-0 z-50"
      x-on:keydown.escape.stop="handleEscape()"
    >
      <!-- Backdrop -->
      <template x-if="showBackdrop">
        <div
          x-cloak
          x-show="isOpen"
          x-transition.opacity
          class="fixed inset-0 bg-gray-900/60"
          aria-hidden="true"
          x-on:click="handleBackdropClick()"
        ></div>
      </template>

      <!-- Panel — slides in from the right -->
      <div
        x-cloak
        x-show="isOpen"
        x-trap.noscroll="isOpen"
        x-transition:enter="transform transition-transform duration-300 ease-out"
        x-transition:enter-start="translate-x-full"
        x-transition:enter-end="translate-x-0"
        x-transition:leave="transform transition-transform duration-200 ease-in"
        x-transition:leave-start="translate-x-0"
        x-transition:leave-end="translate-x-full"
        role="dialog"
        aria-modal="true"
        x-bind:aria-labelledby="dialogTitleId || null"
        class="fixed top-0 right-0 h-full w-full max-w-md bg-white shadow-xl"
      >
        <h2 x-bind:id="dialogTitleId || null">Settings</h2>
        <button type="button" x-on:click="closeDialog()">Close</button>
      </div>
    </div>
  </template>
</div>
```

For a left-side slide-over, position the panel with `left-0` and swap the enter/leave translate classes to `-translate-x-full`.

## Behavior Contract

- `init()` derives `dialogTitleId` from `dialogId` as `${dialogId}-title`, and `dialogDescriptionId` as `${dialogId}-description`, otherwise both `null`.
- `openDialog()` sets `isOpen = true` and dispatches open event(s).
- `closeDialog()` sets `isOpen = false` and dispatches close event(s).
- `toggleDialog()` flips open state by delegating to `openDialog()` and `closeDialog()`.
- `isPersistent` disables both Escape and backdrop close via computed flags.
- `isSeamless` hides backdrop via `showBackdrop`.
- `openDialog()` remembers the focused element. After `closeDialog()`, when `returnFocusOnClose` is `true`, focus returns to that element if it was lost (for example to `<body>` after a leave transition). If something else takes focus first, it is left alone.
- Event names are scoped when `dialogId` exists.

## Error Handling

- Dialog methods are defensive and do not throw for repeated calls (`openDialog()` while open, `closeDialog()` while closed).
- Unknown event listeners or missing external handlers do not block internal state transitions.

## Accessibility Notes

- Keep modal container with `role="dialog"` and `aria-modal="true"`.
- Provide a visible or screen-reader title and wire `aria-labelledby` to that element.
- `dialogTitleId` and `dialogDescriptionId` are only derived when a `dialogId` is passed. **Set a `dialogId` (or add a static `aria-label`) so the dialog has an accessible name** — without one, `aria-labelledby` resolves to `null` and screen readers announce an unnamed dialog.
- Associate descriptive body copy with the dialog by wiring `aria-describedby` to `dialogDescriptionId` so screen readers announce it alongside the title.
- Keep close controls as labeled `button` elements with `type="button"`, and give icon-only close buttons enough padding to meet a comfortable touch-target size.
- Leave `returnFocusOnClose` enabled so keyboard users land back on the control that opened the dialog, including when the dialog is closed from a leave transition or from another component (such as a command palette).
- Use keyboard escape handling (`x-on:keydown.escape.stop`) and focus trapping (`x-trap`) so keyboard users remain inside the modal while open.

## Notes

- Events emitted:
  - `hux-dialog:{dialogId}:open`
  - `hux-dialog:{dialogId}:close`
  - `hux-dialog:open` and `hux-dialog:close` when `dialogId` is missing

## Registration Source

Copy these files as they are. They are the source of truth for every option, default and event above.

### `huxDialog`

```js
document.addEventListener('alpine:init', () => {
  Alpine.data('huxDialog', (initialConfig = {}) => ({
    isOpen: initialConfig.startsOpen ?? false,
    dialogId: initialConfig.dialogId ?? null,
    isPersistent: initialConfig.isPersistent ?? false,
    isSeamless: initialConfig.isSeamless ?? false,
    returnFocusOnClose: initialConfig.returnFocusOnClose ?? true,
    dialogTitleId: null,
    dialogDescriptionId: null,
    _dialogOpenerElement: null,

    get closeOnBackdrop() {
      return !this.isPersistent
    },

    get closeOnEscape() {
      return !this.isPersistent
    },

    get showBackdrop() {
      return !this.isSeamless
    },

    init() {
      this.dialogTitleId = this.dialogId ? `${this.dialogId}-title` : null
      this.dialogDescriptionId = this.dialogId ? `${this.dialogId}-description` : null
    },

    openDialog() {
      if (!this.isOpen) {
        this._dialogOpenerElement = document.activeElement
      }

      this.isOpen = true
      this.dispatchDialogEvent('open')
    },

    toggleDialog() {
      if (this.isOpen) {
        this.closeDialog()
        return
      }

      this.openDialog()
    },

    closeDialog() {
      const wasOpen = this.isOpen

      this.isOpen = false
      this.dispatchDialogEvent('close')

      if (wasOpen) {
        this.restoreOpenerFocus()
      }
    },

    restoreOpenerFocus() {
      const openerElement = this._dialogOpenerElement

      this._dialogOpenerElement = null

      if (!this.returnFocusOnClose || !openerElement?.isConnected) {
        return
      }

      // `x-trap` usually returns focus itself, but a leave transition keeps the
      // focused element visible until it ends, and focus then drops to the body.
      // Watch for up to a second: restore focus once it is lost, and stop as soon
      // as something else moves it.
      const focusedAtClose = document.activeElement
      const watchDeadline = performance.now() + 1000

      const watchFocus = () => {
        const activeElement = document.activeElement
        const isFocusLost =
          !activeElement ||
          activeElement === document.body ||
          activeElement.checkVisibility?.() === false

        if (isFocusLost) {
          openerElement.focus()

          return
        }

        if (activeElement === focusedAtClose && performance.now() < watchDeadline) {
          requestAnimationFrame(watchFocus)
        }
      }

      this.$nextTick(watchFocus)
    },

    handleBackdropClick() {
      if (this.closeOnBackdrop) {
        this.closeDialog()
      }
    },

    handleEscape() {
      if (this.closeOnEscape) {
        this.closeDialog()
      }
    },

    dispatchDialogEvent(eventName) {
      const scopedEventName = this.dialogId
        ? `hux-dialog:${this.dialogId}:${eventName}`
        : `hux-dialog:${eventName}`

      this.$dispatch(scopedEventName, {
        dialogId: this.dialogId,
      })
    },
  }))
})
```
