I have a form with an search input field as laravel livewire component. I want to search suggestions (other component) to be shown if the user clicks into the field or if the user tabs into the field. So I added wire:focus="handleFocus", which emits an event for the suggestions component to show. Works fine so far.
If the field has focus and the user clicks in the field again the suggestions should hide again. wire:focus does not trigger so I added wire:click="handleClick". So I ended up with
<input type="text" wire:model="searchTerm" wire:focus="handleFocus" wire:click="handleClick">
It works for the case that a user tabs into the field: suggestions appear, then clicks into the field: suggestions disappear. Good.
Problem: If a user clicks into the field, both event handlers wire:focus and wire:click are triggered so the field appears and immediately disappears again.
I already spent hours playing with debounce, prevent, adding timer to my component but without any success. In CSS there is :focus-visible which would solve the problem actually but I could not find something like for Javascript.
My stack also includes Javascript/AlpineJS if it helps finding a solution.
Your issue resides in the fact that the click event triggers a focus. Lucky for you, Livewire has access to JS methods and data, therefore you can access the active element. If we combine the mousedown event with your click event, we can pass some data to determine if the handleClick should be processed:
<input type="text" wire:model="searchTerm" wire:focus="handleFocus"
wire:mousedown="handleMousedown(document.activeElement.getAttribute('id')"
wire:click="handleClick($event.currentTarget.getAttribute('id'))">
Then, in your component:
public $activeElementId = null;
public function handleMousedown($activeElementId)
{
$this->activeElementId = $activeElementId;
}
public function handleClick($inputId)
{
if ($this->activeElementId == $inputId) {
// Do Stuff
}
}
This works because mousedown triggers before focusing the element. This will send the active element's ID to your component. If this is the same as your input, then you know that the input was already focused.