Writing An AlpineJS-Extension

Writing An AlpineJS-Extension

A Real-Life Example For A Custom Directive

I would like to show you how easy it is to extend AlpineJS with a small example. The small example implements a timeout directive, which can be used to execute an action after a certain time.

To create your own directive, you need this simple snippet:

import Alpine from 'alpinejs';

document.addEventListener('alpine:init', () => {
  // create a x-timeout directive
  Alpine.directive('timeout', (el, { value, modifiers, expression }, { Alpine, effect, cleanup }) => {

  // Your code

  })
})

window.Alpine = Alpine;
Alpine.start();

First we need to extract the parameters passed to x-timeout. We leave it at a very simple check.

  const timeout = Number(modifiers[0].split('ms')[0]);
  if (!timeout) { return; }

Now we can set the timer and the given expression will be executed if the timer is expired.

let timeout_id = setTimeout(evaluateLater(expression), timeout)

Always tidy up.

cleanup(() => clearTimeout(timeout_id))

And that's it! How simple it is! Even with this small example you can easily extend your website and for example present a modal to request for a newsletter subscription.