2

Is it possible to detect what text has been selected in a text area using Javascript? I'm looking to show the user controls only when they have selected text

Anthony
  • 21
  • 1
  • 2
  • Possible duplicate of http://stackoverflow.com/questions/401593/javascript-textarea-selection ? – pioto Mar 19 '11 at 01:49

2 Answers2

2

I've written a cross-browser function for getting the text selected in a textarea or text input and after some toing and froing the final version is I think the best one I've seen. I've posted it on Stack Overflow a few times before. Here's one example: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?

To detect when the user makes a selection in a textarea, you can use the select event:

var textarea = document.getElementById("some_id");
textarea.onselect = function() {
    var selection = getInputSelection(textarea);
    var selectedText = textarea.value.slice(selection.start, selection.end);
    console.log("Selected text: " + selectedText);
};
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

Yes, you can. It would be as simple as:

const textarea = document.querySelector("textarea")

textarea.addEventListener("select", () => {
  const selection = textarea.value.substring(
    textarea.selectionStart,
    textarea.selectionEnd
  )

  console.log('Your selection:', selection)
})

See MDN.

luvejo
  • 347
  • 2
  • 9