最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to give autofocus to a element when another element has it? - Stack Overflow

programmeradmin2浏览0评论

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 0
Add a comment  | 

2 Answers 2

Reset to default 9

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>

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>

发布评论

评论列表(0)

  1. 暂无评论