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:
JavaScript
x
2
1
Autofocus processing was blocked because a document already has a focused element.
2
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
JavaScript
1
7
1
function focus1() {
2
document.getElementById('ele1').focus()
3
}
4
5
function focus2() {
6
document.getElementById('ele2').focus()
7
}
JavaScript
1
5
1
<textarea id="ele1"></textarea>
2
<textarea id="ele2"></textarea>
3
4
<button onclick="focus1()">Click to focus inp1</button>
5
<button onclick="focus2()">Click to focus inp2</button>