AlpineJS: Dispatching Events Outside the Parent Div
CHow to use AlpineJS to dispatch events from an element outside its parent-child relationship.

- Fauzan My
- 2 min read

When manipulating HTML elements with the help of the AlpineJS framework, interactions typically occur within a single family block. For example, a parent element can usually command its child elements.
<div x-data="{ open: false }"> <!-- parent element -->
<button @click="open = true">Expand</button> <!-- child element -->
<span x-show="open"> <!-- child element -->
Content...
</span>
</div>
But what if parent or child elements could interact with elements outside their family structure? In other words, what if a child could give instructions to a neighboring child or even to the village chief?
The solution is straightforward: use the $dispatch()
function in AlpineJS. “$dispatch is a helpful shortcut for dispatching browser events,” as stated in the AlpineJS.dev documentation.
Here’s how to use it:
<!-- Parent child element -->
<div x-data>
<button @click="$dispatch('open-neighbor-element')">Click Message</button>
</div>
<!-- ./Parent child element -->
<!-- Parent child neighbor element -->
<div x-data="{ open: false }" x-show="open" @open-neighbor-element.window="open = !open">
<p>
I have received a message from your father.
</p>
</div>
<!-- ./Parent child neighbor element -->
Live Demo
Explanation of the code:
-
The line of code @click="$dispatch(‘open-neighbor-element’)" binds the value to an HTML attribute outside the parent-child relationship.
-
In the next div element, the attribute @open-neighbor-element.window=“open = !open” is the target for the interaction.
I hope this helps!
References: