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.
let textArea = document.getElementById('textArea')
let display = document.getElementById('display')
let getSelectedText = () => {
let selectedText = textArea.value
let selStart = textArea.selectionStart
let selEnd = textArea.selectionEnd
return selectedText.substring(selStart, selEnd)
}
textArea.addEventListener('select', () => {
display.innerHTML = `<b>Your selected text is:</b> <i>${getSelectedText()}</i>`
})
<textarea id='textArea' rows="7" 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>