Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
Can't focus with jQuery?

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 :)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

use setTimeout to wait animation complete

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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);
about 4 years ago · Juan Pablo Isaza Relatório

0

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)
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda