Mia
Mia

Reputation: 6531

Html input, always in focus

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 focus on the object. Is there any simple way to keep the focus there?

Upvotes: 18

Views: 54349

Answers (4)

danieltan95
danieltan95

Reputation: 860

For react and the like:

<input  type={'text'}  autoFocus={true} onBlur={({ target }) => target.focus()}/>

Upvotes: 17

Schleicher
Schleicher

Reputation: 196

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.

Upvotes: 0

Saad Joudi
Saad Joudi

Reputation: 623

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 >

Upvotes: 3

soktinpk
soktinpk

Reputation: 3888

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.

Upvotes: 43

Related Questions