Livewire: Set focus

Created on 10 Nov 2019  路  3Comments  路  Source: livewire/livewire

Hi, I was just looking through the docs, and a super common use case for me on a page is setting the focus somewhere after I have a click event. Is there a way to deal with this in livewire, or defer to local JS? Can I defer to local after calling an event on the package? Maybe a quick docs page on this might be helpful.

Cheers

Most helpful comment

Nice! That javascript solution looks perfect! I'll give it a try shortly! I think I need to re-read the docs if I missed that.

All 3 comments

Hi @roni-estein , if I understand you correctly, that you are adding new elements and want to immediately set autofocus for them.

Please see this example:

namespace App\Http\Livewire\Foo;

use Livewire\Component;

class Bar extends Component
{
    /**
     * @var bool
     */
    public $isOpenProfileForm = false;

    /**
     * @return \Illuminate\View\View
     */
    public function render()
    {
        return view('livewire.foo.bar', [
            'isOpenProfileForm' => $this->isOpenProfileForm,
        ]);
    }

    /**
     * @return void
     */
    public function openForm()
    {
        $this->isOpenProfileForm = true;
    }
}

This is a simple form that simulates a situation in which, by clicking on the button, a modal window appears, where the input field will be offered to the user to fill in automatically.

<div>
    <button wire:click="openForm">Edit Profile</button>

    @if($isOpenProfileForm)
        <div class="modal">
            <input name="first_name" autofocus>
        </div>
    @endif
</div>

This is what you need?

Here's a way you can hook into Livewire events and do things with JS:

Blade Template:

<div class="pt-8 w-48">
    <button wire:click="increment">+</button>
    <button wire:click="decrement">-</button>

    <input type="text">

    {{ $count }}
</div>

@push('scripts')
<script>
    window.addEventListener('livewire:load', () => {
        @this.on('incremented', () => {
            document.querySelector('input').focus()
        })
    })
</script>
@endpush

Relevant Parts Of Component:

    public function increment()
    {
        $this->count++;

        $this->emit('incremented');
    }

Nice! That javascript solution looks perfect! I'll give it a try shortly! I think I need to re-read the docs if I missed that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

austenc picture austenc  路  3Comments

pmartelletti picture pmartelletti  路  3Comments

cloudstudio picture cloudstudio  路  3Comments

stefro picture stefro  路  3Comments

tanthammar picture tanthammar  路  3Comments