Home > database >  Can't focus with jQuery?
Can't focus with jQuery?

Time:11-18

I'm trying to focus on input when the search icon is clicked so the user can start typing without having to click on the input manually. Ideally, it should be something like this, but focus() doesn't work on this input for some reason.

$('.header__icons a[role="button"]').click(function(){
     $('#q').focus();
})

I've tried various options, but nothing..I see this input gets "focus-visible" and "data-focus-visible-added" when clicked on. I tried adding them manually, but it doesn't focus it either. I also couldn't locate any functions related to this in the files.

EDIT: The code works fine, just added setTimeout..and dev console was the reason I wasn't seeing any changes here :)

CodePudding user response:

Actually, the code you have should work. I recommend you close the browser's developer console and test it again. The reason it probably doesn't work is that focus() doesn't steal focus from the dev console.

Try using a setTimeout in the dev console and then quickly click in your browser window, then you should see it focus the search box.

setTimeout(function() { $('input[name="q"]').focus() }, 3000);

CodePudding user response:

use setTimeout to wait animation complete

$('.header__icons a[role="button"]').click(function() {
  setTimeout(function() {
    $('#q').focus();
  }, 1000)
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The problem is that when the user clicks the button, the field is not yet visible, so it cannot be focused. It will be visible in the next tick though (doesn't matter that it's transparent - it's about whether it's rendered at all or not), so you can use setTimeout with a timeout of zero:

$('.header__icons a[role="button"]').click(function(){
     setTimeout(() => $('#q').focus(), 0)
})
  • Related