Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move a DOMElement while preserving focus?

Suppose I have a simple HTML page with a textarea, and I want to wrap that textarea in a DIV. However, this doesn't always happen on startup / page load, so the user might have focus in that area, or even be typing.

I can move / wrap the area by creating a DIV, appending it to the textarea's parent, then putting the textarea inside of it, and it works great. However, when I do that, focus is removed from the textarea and if the user was in the middle of typing, they're going to get angry.

How can I move the textarea's DOM node without interrupting the user? Is this even possible?

like image 606
Coderer Avatar asked Feb 23 '23 12:02

Coderer


1 Answers

Depending on the browser you may be able to determine which element has focus by using document.activeElement. Save the value before performing the move and then afterwards set the focus back using .focus() in the textarea is the same element as what you saved.

like image 181
Jason Avatar answered Feb 28 '23 00:02

Jason