0

I am selecting a text to copy it by using window.getSelection().addRange(range):

  var targetelement = document.getElementById("someid"), 
  range = document.createRange();
  range.selectNode(targetelement);
  window.getSelection().addRange(range);
  document.execCommand('copy')

It works, but the browser(firefox) selects the text inside the tag after the completion of the code. How can I diselect it? Is there some kind of opposite to window.getSelection function or method?

smus
  • 133
  • 1
  • 3
  • 14
  • 1
    Can you just select "" to 'diselect it'? Also can you show what Firefox is doing versus what you want to happen? – dustytrash Sep 19 '18 at 13:40
  • 1
    Most likely a dupe of https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript – epascarello Sep 19 '18 at 13:40
  • 3
    Possible duplicate of [Clear Text Selection with JavaScript](https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript) – dustytrash Sep 19 '18 at 13:41

3 Answers3

1
<div id="someid">
This is a test man
</div>

<div id="empty">
</div>


<script>
    var targetelement = document.getElementById("someid");
    var  range = document.createRange();
  range.selectNode(targetelement);
  window.getSelection().addRange(range);
  document.execCommand('copy');  

   window.getSelection().removeAllRanges();
</script>

https://jsfiddle.net/s1teLukn/5/

Menelaos
  • 23,508
  • 18
  • 90
  • 155
1

After copy trigger a focus or blur to this input field to diselect the text.

domready
  • 252
  • 1
  • 6
1

This old code works in all browsers:

var sel = window.getSelection ? window.getSelection() : document.selection;

if (sel) {
    if (sel.removeAllRanges) {
        sel.removeAllRanges();
    } else if (sel.empty) {
        sel.empty();
   }
}