Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!