Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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');
}
like image 689
mpurkaye Avatar asked Oct 04 '20 02:10

mpurkaye


People also ask

How do I get selected text option in select?

To get the text of the selected option, we first need to find the selected option using the find() method and then use the text() method to get the option text. where selectBox is the value of the id attribute of the <select> HTML tag.

What event occurs when user highlights text in text field?

The onselect event occurs after some text has been selected in an element. The onselect event is mostly used on <input type="text"> or <textarea> elements.

When user make a selection in the HTML select list event is raised?

When user makes a selection in the HTML select list, on cho vent is raised. 3. The property for an ID is referred to by. operator.

Which event occurs when the user selects a HTML item?

Class ItemEvent. A semantic event which indicates that an item was selected or deselected.


1 Answers

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>
like image 59
sandeep joshi Avatar answered Sep 30 '22 17:09

sandeep joshi