AlpineJS: Dispatching Events Outside the Parent Div

CHow to use AlpineJS to dispatch events from an element outside its parent-child relationship.

Illustration
Illustration

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:

comments powered by Disqus
Fauzan My avatar

Written by Fauzan My

Iam obsessed with elegant and simple design, whether it involves complex creative processes or simplicity. Here, I combine both: design and coding, searching for best practices.

More from Fauzan My

Smartphone twitter Icon X social media.
Twitter Icon X in SVG Bootstrap
Visual Studio Code.
Problem solving: Hugo WARN Module is not compatible
HTML pseudo element.
How to Create Article Card Links