Useful Alpinejs Code Snippets

To change the value of any of the attributes with the help of x-bind:

<a x-bind:href="'/home/' + id"  x-text="id"  id="id">Click Here</a>

To change the value of the text with the help of x-text:

<span x-ref="userid"  x-text="id"></span>

To call a Livewire controller function on the click of a button with @click and $wire:

<button x-text="id"  @click="$wire.check(id)">Check Now</button>

To implement a quick flash message div

<div x-data="{ show: true }"  x-show="show"  x-init="setTimeout(() => show = false, 3000)"></div>

Click to edit (convert a label into a text box)

<div class="mt-4 flex justify-between items-center"  x-data="{ open: false, close: true }">
        <label for="name"  value="{{ __('Name ')  }}">{{ __('Name: ')  }}</label>
        <span x-show="close"  class="inline w-2/3 font-semibold text-indigo-600">{{  $user->name  }}</span>
        <x-input x-show="open"  id="name"  type="text"  name="name"  value="{{  $user->name  }}"  />

    <button x-on:click="open = ! open; close = ! close"  type="button"  class="inline border border-gray-400 p-2 rounded-sm">
        <svg xmlns=""  fill="none"  viewBox="0 0 24 24"  stroke-width="1.5"  stroke="currentColor"  class="w-6 h-6">
            <path stroke-linecap="round"  stroke-linejoin="round"  d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"  />

Fire a JS function on page load

<div x-init="fire(3)" ></div>

    function fire(sample) {
        console.log('Cube of ' + sample + ' is ' + sample*sample);

Confirmation modal window leveraging confirm() method

When a user clicks the button, it will fire the JS confirm dialog

    onclick="confirm('Are you sure?')  ||  event.stopImmediatePropagation()"
    Delete User