Search code examples
javascripthtmlfocus

Keep a text field focused despite clicking elsewhere


I want to keep the text field focused, despite clicking on the red div. I try different methods, why nothing works?

function stopEvent(e) {
   e.stopPropagation();
   e.preventDefault();
   return false;    
}
function setFocus(e) {
   document.getElementById("textField").focus();
   stopEvent(e);
}
document.getElementById("textField").focus();
<div onmouseover="setFocus(event);" onfocus="this.blur();">
  <div style="background-color:red; height:100px;" onclick="stopEvent(event)" onfocus="this.blur();">Click area</div>
  <div><input id="textField" type="text" value="focused" /></div>
</div>
  
  


Solution

  • You used stopEvent instead of setFocus on your click area div. Also you didn't return false in the setFocus so the return false in stopEvent was useless.

    function stopEvent(e) {
       e.stopPropagation();
       e.preventDefault();
       return false;    
    }
    function setFocus(e) {
       document.getElementById("textField").focus();
       return stopEvent(e);
    }
    document.getElementById("textField").focus();
    <div onmouseover="setFocus(event);" onfocus="this.blur();">
      <div style="background-color:red; height:100px;" onclick="setFocus(event)" onfocus="this.blur();">Click area</div>
      <div><input id="textField" type="text" value="focused" /></div>
    </div>