How to get text value of selected text from onSelect DOM event

Viewed 460

Think this is a simple question, but I am very new to web dev so I apologize :) -> on an onSelect event, how do I grab the content of what was selected? And is there a way to modify the text that was selected, such as highlighting?

This is what I have so far:

<textarea id="text">
Text to be highlighted
</textarea>

in js:

let text_selection   = document.getElementById("text");
text_selection.addEventListener("select", highlightText);

function highlightText(){
  alert('hello');
}
2 Answers

You can get the starting and ending offset of the selection from the event target, and use substring to figure out the selection

text_selection.addEventListener("select", highlightText);

function highlightText(event){
    let textarea = event.target;
    let selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
    alert(selection)
    // ^^ don't use alert
    console.log(selection); 
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event

to grab the selected text you can use textarea.selectionStart and textarea.selectionEnd as mentioned in another answer

To solve second part of the question you will need some CSS rule to highlight the selected text. please check the code snippet.

let text_selection = document.getElementById("text");
text_selection.addEventListener("select", highlightText);

function highlightText() {
  let textarea = event.target;
  let selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
  console.log(selection)
}
::-moz-selection {
  color: yellow;
}

::selection {
  color: yellow;
}
<textarea id="text">
Text to be highlighted
</textarea>

Related