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');
}
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.
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 makes a selection in the HTML select list, on cho vent is raised. 3. The property for an ID is referred to by. operator.
Class ItemEvent. A semantic event which indicates that an item was selected or deselected.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With