The user will enter text into a HTML textarea on the page. When they highlight part of that text, how can I access the highlighted string? Are there any events triggered by highlighting of text in a textarea element?
This is being done in the context of a react app where the textarea is a component.
Create a function that takes the value of your text area and gets the start and end using el.selectionStart and el.selectionEnd, then use el.substring() to get the selected text within the defined constraints for start and end.
Lastly, run the function within an eventlistener that is listening to the text areas select event.
const textArea = document.getElementById('textArea')
const display = document.getElementById('display')
const getSelectedText = () => {
return textArea.value.substring(textArea.selectionStart, textArea.selectionEnd)
}
const displayText = () => {
display.innerHTML = `<strong>Your selected text is:</strong> <em>${getSelectedText()}</em>`;
}
textArea.addEventListener('select', displayText)
<textarea id='textArea' rows="5" cols="50">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>
<div id="display"></div>
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