How can I keep the html input always in focus?
Using the autofocus
attribute when creating the element helps to focus at pageload, but it does not keep the focu
For FIREFOX, Try using setTimeOut, it works :
My JS :
myFocusFunction(){
let myInput = document.getElementById('idOfInput');
setTimeout(function() {
myInput .focus();
}, 100);
}
my Html :
<input type="text" ng-blur="myFocusFunction()" auto-focus >
What worked for me was using the autofocus
attribute on the HTML input to focus it on initial page load, and then disabling all mousedown events:
document.onmousedown = (e) => {
e.preventDefault();
}
Obviously if you need to support mouse events, you'd want a less drastic approach, but it fit my use case for a command-line emulator web app.
Try this:
<!-- On blur event (unfocus) refocus the input -->
<input onblur="this.focus()" autofocus />
<input value="Can't focus on this" />
Basically, you add a blur
event (which occurs whenever the input loses focus), and in the blur event, you focus on the input. In addition, you add the autofocus
attribute to start off focused as well.
P.S. If you are planning to use this for a website for actual people to use, from a user interface perspective, this is probably not a great idea.
For react and the like:
<input type={'text'} autoFocus={true} onBlur={({ target }) => target.focus()}/>