bastinald / laravel-livewire-modals

Dynamic Laravel Livewire Bootstrap modals.
66 stars 31 forks source link

Autofocus on input within Modal #2

Closed MACscr closed 2 years ago

MACscr commented 3 years ago

Double checked some of your existing modals and even tried adding autofocus to an input, but no dice. I think there needs to be a way to autofocus on the first input opening a form within a modal. Thoughts? I opened it here because i figured it would apply to this package and your ui package.

Thiktak commented 3 years ago

Hello,

I had the same need for some of my modals (but not all of them).

I found a ways for this : Add on your JS file, an event listener for "shown.bs.modal" and focus() the first input. (even better could be to focus the first element with autofocus HTML5 property)

let modalsElement = document.getElementById('laravel-livewire-modals');
modalsElement.addEventListener('shown.bs.modal', (e) => {
    let elt = e.target.querySelectorAll('input,select,textarea');
    if( elt && elt.length > 0 ) {
        elt[0].focus();
    }
});

Maybe something like that ?

let modalsElement = document.getElementById('laravel-livewire-modals');
modalsElement.addEventListener('shown.bs.modal', (e) => {
    let elt = e.target.querySelectorAll('*[autofocus=true],*[autofocus="autofocus"]');
    if( elt && elt.length > 0 ) {
        elt[0].focus();
    }
});
bastinald commented 2 years ago

as mentioned above, can be done with JS via the shown.bs.modal listener