khanistropos khanistropos - 27 days ago 9
jQuery Question

Autofocus not working ok when elem shows up

I'm not getting autofocus on the input when it shows up.
The autofocus property works intermitently on Chrome.
On IE11... well it does not even try to add it.

Do I need to validate the existence of the input element on the DOM before apply the autofocus with jQuery?

HTML5

<input type="text" class="form-control" autofocus placeholder="Filter">


JS

function iboxHistorySearch() {
var header = $('.client-history .ibox-title_replace'),
searchbar = $('.client-history .client-history-searchbar'),
closeBtn = $('.client-history .btn-dismiss');

header.on('click', function (e) {
e.preventDefault();
if (searchbar.hasClass('hidden')) {
searchbar.removeClass('hidden')find('form-control:first').focus();
$(this).addClass('hidden');
}
});

closeBtn.on('click', function (e) {
e.preventDefault();
if (header.hasClass('hidden')) {
header.removeClass('hidden');
searchbar.addClass('hidden');
}
});
}

iboxHistorySearch();


UPDATE

searchbar.removeClass('hidden')find('form-control:first').focus();

Answer

From the (unedited) question:

var searchbar = $('.client-history .client-history-searchbar')

if (searchbar.hasClass('hidden')) {
    searchbar.removeClass('hidden').focus();

make sure that searchbar is an input control that can receive focus. If not, add a .find to get an input, either the first or a specific element, eg:

    searchbar.removeClass('hidden')
             .find('.form-control:first')
             .focus();

or

    searchbar.removeClass('hidden')
             .find('input:first')
             .focus();

(but with input you may also need to add checkbox/select etc, eg)

    searchbar.removeClass('hidden')
             .find('input,select,textarea')
             .first()
             .focus();