0

I would like to copy text in the input field but without highlighting selected text. Below is the code snippet,

click = () => {
    this.input_ref.current.select();
    document.execCommand('copy');
};

<input readOnly ref={this.input_ref} value="hello"/>
<button onClick={this.click}>COPY</button>

I have tried add css to input field as below but did not work.

.no_select {
-webkit-tap-highlight-color: transparent;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
outline: none;
}
<input classname="no_select" readOnly ref={this.input_ref} value="hello"/>

Could someone help me with this. thanks.

sujana
  • 135
  • 1
  • 3
  • 11

1 Answers1

1

I found answer to my question and thought would help others too. So posting an answer here. On clicking copy button after copying the text to clipboard i used window.getSelection().removeAllRanges() to deselect the text in input field. Below is the code snippet,

click = () => {
   this.input_ref.current.select();
   document.execCommand('copy');
   window.getSelection().removeAllRanges();
};

EDITED: Above above only for chrome and not on IE11 so used the below lines which works both on chrome and IE11 to deselect text in input field.

document.getSelection().removeAllRanges();
document.getSelection().addRange(document.createRange());
sujana
  • 135
  • 1
  • 3
  • 11