I'm trying to make a wrapper with text tags in textarea, while reading https://learn.javascript.ru/range-textrange-selection at the same time, but my focus is lost when I click on the button, and on the Internet I’m asked mostly how to remove the focus when clicked)

The citizen had the same misfortune, but my focus is still lost.

document.querySelector('button').onclick = e => { e.preventDefault(); console.log(getSelection().toString()); } 
 <textarea name="" id="" cols="30" rows="10">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet laudantium eum ipsam repudiandae assumenda praesentium, aliquam ab, consectetur, voluptate adipisci odio. Commodi ad doloribus unde sit eos cum architecto quis distinctio tempora rem sequi, voluptate quaerat repellendus veniam officiis! Porro minima voluptate placeat velit, ab numquam ex voluptatem tenetur quae!</textarea> <button type="button">Click Me</button> 

PS Just that I realized that the focus is lost with the textarea, if you select plain text, then everything is fine.

  • It is necessary to cram in the iframe textarea. There, the selection will not disappear. The truth is all the more complicated with this incredible. Yes, you can see it right on this page. If you run the example, select the text and click outside the example, the selection will remain, only change the color to faded. And all because the example runs in the iframe. - Sergey

1 answer 1

It is necessary to do this:

 <textarea id="mytextarea">asdasd asdfsdf asdfsdf dsafsdf</textarea> <button onclick="getSel()">Click</button> <script type="text/javascript"> function getSel() // javascript { var txtarea = document.getElementById("mytextarea"); var start = txtarea.selectionStart; var finish = txtarea.selectionEnd; var sel = txtarea.value.substring(start, finish); console.log(sel); } </script> 
  • Oh clear, did not know about such properties textarea. - DimenSi
  • I wanted to give my answer, but now I broke. - DimenSi