Hooks for Alpine.js

Packages

June 7th, 2023

Hooks for Alpine.js

The Alpine Hooks module is a collection of hooks for use with Alpine.js. This package contains a variety of hooks used to improve the developer experience (DX) for common Alpine tasks.

At the time of writing this module has the following hooks:

  • $useHover() - react to the mouse hovering over an element
  • $useFocus() - react to an element being focused and blurred
  • $useHash() - update and react to changes to window.location.hash
  • $useWindowSize() - returns the window width and height and react to changes to window size

Here's an example of $useHover() from the examples folder on GitHub:

<div x-data="{ hovering: $useHover($refs.target) }" class="py-8">
<div
class="w-52 h-64 rounded bg-red-500 transition-colors ease-in-out duration-300 mx-auto flex items-center justify-center"
x-bind:class="{
'bg-red-500': !hovering,
'bg-blue-500': hovering
}"
x-ref="target"
>
<p class="font-medium" x-text="hovering ? 'Hovering...' : 'Not hovering...'"></p>
</div>
</div>

You can install this package in your project with npm:

npm install @ryangjchandler/alpine-hooks

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.