1
<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

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • You didn't define `txtCmd` and `txtKeyword`. You can use CSS `pointer-events: none` in the `topDiv`. – Raptor Feb 22 '22 at 02:13
  • 1
    Tried your codes, the `topDiv` never gets focused (as it's a DIV rather than a form element). – Raptor Feb 22 '22 at 02:19
  • Disadvantages of using `pointer-events`: https://stackoverflow.com/questions/3680429/click-through-div-to-underlying-elements – Raptor Feb 22 '22 at 02:24
  • @Raptor, thanks! I tried again, it's the body gets focus, rather than topDiv. – Zhang Feb 22 '22 at 02:37

1 Answers1

0

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

setTimeout(function(){
        if(document.activeElement === txtCmd){
            return;
        }
        txtKeyword.focus();
      }, 100);
Zhang
  • 3,030
  • 2
  • 14
  • 31