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

160
Visualizações
Check which element is clicked when page gets focus
<div id="topDiv">
    <input id="txtKeyword" type="text" />   
</div>

My purpose is to make txtKeyword getting focus when the page gets focus. My code,

 window.addEventListener("focus", function(event) {
      setTimeout(function(){
        txtKeyword.focus();
      }, 100);
    });

That works pretty well when there is only one text element there. When I add another text element,

<div id="topDiv">
    <input id="txtCmd" type="text" /><input id="txtKeyword" type="text" />     
</div>

when I click txtCmd to make the page getting focus, I don't want the focus is reset to txtKeyword, just leave to txtCmd. My code,

window.addEventListener("focus", function(event) {
        if(document.activeElement === txtCmd){
            return
        }
      setTimeout(function(){
        txtKeyword.focus();
      }, 100);
    });

I try to compare if the current focused element is txtCmd, if so, return. However, when the page gets focus via clicking txtCmd, the focused element is topDiv rather than txtCmd. How do I check if I really click txtCmd?

Edit:

  1. I forgot to mention, all the element txtCmd or txtKeyword I have defined global variables and assigned the values in onload event.

  2. The document.activeElement is body rather topDiv, my fault. enter image description here

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

0

For this particular question, put the check in the timeout function can do

setTimeout(function(){
        if(document.activeElement === txtCmd){
            return;
        }
        txtKeyword.focus();
      }, 100);
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