Can I move DOMElement while maintaining focus?

Suppose I have a simple HTML page with textarea and I want to wrap this textarea in a DIV. However, this does not always happen when loading / loading a page, so the user may have focus in this area or even print.

I can move / wrap the area by creating a DIV, adding it to the textarea parent and then putting the textarea inside, and it works fine. However, when I do this, the focus is removed from textarea , and if the user is in the middle of typing, they will get angry.

How can I move the textarea DOM node without interrupting the user? Is it possible?

+4
source share
4 answers

Depending on the browser, you can determine which element has focus using document.activeElement. Save the value before moving, and then set the focus back using .focus () in the text box - this is the same element that you saved.

+4
source

Well, reorienting (using focus() ) is one thing, but you also want the user cursor to be in the same place (and perhaps his current choice if he did this). Perhaps, however, using the document.selection / range API, see https://developer.mozilla.org/en/DOM/range .

This link describes a solution (a slightly different problem) using this API in IE.

+3
source

You only have to reset focus after moving everything.

Using

 .focus() 

On your text screen after moving.

+1
source

After adding the text box to the div, you just need to call focus on the text box shown in this fiddle

HTML

 <textarea id="test">test</textarea> 

JAVASCRIPT

 var textarea = document.getElementById('test'); setTimeout(function(){ var div = document.createElement('div'); document.body.appendChild(div); div.appendChild(textarea); textarea.focus(); console.log('appended'); },2000); 
0
source

Source: https://habr.com/ru/post/1379382/


All Articles