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?
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?
Share Improve this question edited Aug 31, 2021 at 13:28 Elias Holzmann 3,6692 gold badges20 silver badges38 bronze badges asked Mar 4, 2021 at 6:27 Bash 297Bash 297 1231 gold badge1 silver badge4 bronze badges 02 Answers
Reset to default 9Giving 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>
After adding the textarea
control then set focus to that control.
I thing this will solve your problem.
On button click call addTextArea()
function.
<script type="text/javascript">
var cntctrl = 0;
function addTextArea() {
try {
var s = document.createElement('textarea');
cntctrl = cntctrl + 1;
var id = 'txtarea' + cntctrl;
s.setAttribute('id', id);
s.setAttribute('class', "txtareaclass");
s.setAttribute('rows', "4");
s.setAttribute('cols', "100");
document.body.appendChild(s);
document.getElementById(id).focus();
}
catch (e) {
console.log('Adding Textarea failed!.');
console.log('Error: ' + e);
}
return false;
}
</script>