To execute JavaScript code when clicking a Livewire button, you can use the wire:click directive along with the @this directive to reference the Livewire component. Here's an example:
<button wire:click="toggleInput">Toggle Input</button>
@push('scripts')
<script>
document.addEventListener('livewire:load', function () {
Livewire.on('inputToggled', function () {
// Execute your JavaScript code here
// For example, if you want to initialize intl-tel-input
// you can call the initialization function
initializeIntlTelInput();
});
});
</script>
@endpush
In your Livewire component, you need to define the toggleInput method and emit an event to trigger the JavaScript code execution. Here's an example:
use Livewire\Component;
class YourComponent extends Component
{
public $inputType = 'phone';
public function toggleInput()
{
$this->inputType = ($this->inputType === 'phone') ? 'email' : 'phone';
$this->emit('inputToggled');
}
// ...
}
Make sure to replace YourComponent with the actual name of your Livewire component.
This solution uses the Livewire JavaScript hooks to listen for the inputToggled event and execute the JavaScript code when the event is emitted.