Skip to content
Advertisement

How to give autofocus to a element when another element has it?

I am trying to give a textarea (which is added when you click on a button) autofocus with the autofocus attribute, but when I do that it doesn’t works and I get this message on the console:

Autofocus processing was blocked because a document already has a focused element.

So now the question is: How can I get the focus to the textarea when some other element already has it?

Advertisement

Answer

Giving autofocus to a textarea is basically saying “When the page loads, this textarea should be focused” So focusing another element isn’t a problem: If that error is occurring, just use the .blur() method on the textarea you want to lose focus on. Then do the .focus() method on the one you want focused

function focus1() {
  document.getElementById('ele1').focus()
}

function focus2() {
  document.getElementById('ele2').focus()
}
<textarea id="ele1"></textarea>
<textarea id="ele2"></textarea>

<button onclick="focus1()">Click to focus inp1</button>
<button onclick="focus2()">Click to focus inp2</button>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement