HTMLGuyLLC / jAlert

jQuery alert/modal/lightbox plugin
https://htmlguyllc.github.io/jAlert/
MIT License
76 stars 35 forks source link

Question - Autofocus OK button on alert box #65

Closed Yokomoko closed 5 years ago

Yokomoko commented 5 years ago

Just a question, could not find the answer for on the documentation and same issue occurs here https://htmlguyllc.github.io/jAlert/

We have a textbox where pressing enter runs a search unless the textbox has <3 chars in, in which case open up the alert dialog asking to enter 3 or more characters. We need to be able to quickly press enter to clear the dialog, currently the focus remains on the previous field and re-opens the dialog.

Pressing enter on your example alert dialogs re-opens the dialog too because the last focus is on the button behind. I know you have a confirmAutoFocus: '' for confirmBoxes, is there anything similar for Alert boxes?

HTMLGuyLLC commented 5 years ago

You can add the class "autofocus" to an element and it'll find it and focus on it automatically (from what I remember - without looking at code/docs). Give it a shot and LMK!

Yokomoko commented 5 years ago

AH got it, cheers.

autofocus | false | string (dom selector), false | String should be an element within the alert that you would like autofocused onOpen (good for inputs and buttons).

For anyone else that wants to know the syntax (Took me a few minutes..)

autofocus: '#okayBtn',
btns: [{ text: 'OK', closeAlert: 'true', theme: 'red', id: 'okayBtn' }],

Edit: This focused the OK button but it doesn't focus the textbox that was focused before the box was fired. Had to do a bit of fiddling in jQuery for that:

var lastActiveElement;
$(document).ready(function () {
    $('input').on("focus", function () {
        lastActiveElement = this;
    });
});

And on the onclose event, focus lastActiveElement after everything else that happens:

onClose: function () {
            if (onDismissScript !== "") {
                eval(onDismissScript);
            }
            $(lastActiveElement).focus();
        }
    });