I have a React application which displays some spans:
Hello my name is &l
Step 1: - Initially Mouse will capture every time you enter something
<textarea type="text"
className="contentarea__form__input"
onMouseUpCapture={this.selectedText}>
</textarea>
Step 2: To make sure it only catches your selected text I used if-else condition
selectedText = () => {
window.getSelection().toString() ? console.log(window.getSelection().toString()) : null;
}
Use onMouseUp
and onDoubleClick
events to detect to call method, that will determine selection using JavaScript Selection API.
Use window.getSelection()
to get selection object.
To get selected text, use window.getSelection.toString()
.
To get coordinates of selected text area for rendering popup menu, use selection.getRangeAt(0).getBoundingClientRect()
.
As an example implementation, take a look at react-highlight library.
Due to this bug in Firefox, I was unable to get it working with
window.getSelection()
as suggested by other answers.
So I had to do the following (in React):
constructor(props) {
this.textAreaRef = React.createRef();
}
getSelection() {
const textArea = (this.textAreaRef.current as HTMLTextAreaElement);
console.log(textArea.value.substring(
textArea.selectionStart,
textArea.selectionEnd
)
);
}
render() {
<textarea onMouseUp={() => this.getSelection()}
ref={this.textAreaRef}>
</textarea>
}
Here's an example in React using a functional component:
const Post = () => {
const handleMouseUp() {
console.log(`Selected text: ${window.getSelection().toString()}`);
}
return (
<div onMouseUp={handleMouseUp}>Text</div>
);
}
As Lyubomir pointed out the window.getSelection() API does the trick!
There is no React-specific solution for this. Just use window.getSelection API.
To output highlighted text run window.getSelection().toString()
I think that it's the right way...
document.onmouseup = () => {
console.log(window.getSelection().toString());
};