Alpine.directive()

Register custom directives.

What is Alpine.directive()?

Alpine.directive() allows you to create your own HTML directives. The callback receives the element, the value expression, and any modifiers. It's the most powerful extension point in Alpine.

When to Use

Use Alpine.directive() when you need to add behaviour that isn't covered by built‑in directives – for example, a x‑click‑outside directive or a x‑tooltip.

Simple Directive

Code
Alpine.directive('focus-on-init', (el) => {
  el.focus()
})
// Usage: <input x-focus-on-init>

Directive with Expression

Code
Alpine.directive('log', (el, { expression }) => {
  console.log(eval(expression))
})
// <div x-log="count">

💡 Tip

Custom directives run when Alpine initialises the element. If you need to react to data changes, use Alpine.effect() inside the directive.

Helpful? Share this page!↑ Back to top