How to Use x-on click event in AlpineJS

In this tutorial, we will explore an example of using the x-on or @click event in Alpine.js. We can utilize x-on to listen to DOM events and execute JavaScript when they are triggered.

Example 1

x-on click event syntax.

<div x-data>
    <button x-on:click="alert('Hello World!')">Click Me</button>
</div>
x-on click event

Shorthand syntax.

<div x-data>
  <button @click="alert('Hello World!')">Click Me</button>
</div>

Example 2

For increase and decrease value using click event and x-text.

<div x-data="{ count: 0 }">
    <button x-on:click="count++">Increment</button>
    <button x-on:click="count--">Decrement</button>
    <span x-text="count"></span>
</div>

Example 3

Create toggle button with alpine js using click events.

<div class="flex justify-center mt-8" x-data="{ toggle: '0' }">
    <div class="relative w-12 h-6 transition duration-200 ease-linear rounded"
        :class="[toggle === '1' ? 'bg-green-400' : 'bg-gray-400']">
        <label for="toggle"
            class="absolute left-0 w-6 h-6 mb-2 transition duration-100 ease-linear transform bg-white border-2 rounded cursor-pointer"
            :class="[toggle === '1' ? 'translate-x-full border-green-400' : 'translate-x-0 border-gray-400']"></label>
        <input type="checkbox" id="toggle" name="toggle" class="w-full h-full appearance-none focus:outline-none"
            @click="toggle === '0' ? toggle = '1' : toggle = '0'" />
    </div>
</div>
toggle x-on click event

Example 4

Alpine js hide element and show element using @click event and x-show.

<div x-data="{ open: false }">
    <button @click="open = !open" x-text="open==true  ? 'hide' : 'show'"></button>
    <ul x-show="open">
        <li>Tailwind CSS</li>
        <li>PHP</li>
        <li>Laravel</li>
    </ul>
</div>

You can use create dropdown.

<div x-data="{ open: false }">
    <button @click="open = !open">Dropdown</button>
    <ul x-show="open">
        <li>Tailwind CSS</li>
        <li>PHP</li>
        <li>Laravel</li>
    </ul>
</div>