Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda