Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the currently highlighted text within a <textarea> in Javascript

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.

like image 501
O James Avatar asked Oct 22 '25 04:10

O James


1 Answers

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>
like image 158
dale landry Avatar answered Oct 23 '25 18:10

dale landry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!