Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextArea Selection Change?

How can I get, for a HTML TextArea element, get called back on all selection changes to the text edited therein?

(I am currently using the hack of combining keyup, keypress, and mousemove (for dragging selection endpoint), and maybe more could be added, but this is not exactly elegant.)

Can't find it in HTML docs or on SO.

EDIT: By 'all selection changes' I mean including the continuous change during selecting using the mouse, and also I'd like to get a callback when selection collapses and when there is only a caret that is moved (selection is zero length, but changes). I think there is no other way than to implement this by combining many events. Or even using an interval callback and simply comparing, but is also not really good.

like image 508
Jonas N Avatar asked Oct 09 '17 16:10

Jonas N


2 Answers

What you want is the global selectionchange event available on the window or document. Read about it here.

Add a unique id to your textarea:

<textarea id="unique-id"></textarea>

Add an event listener to the document:

function handleSelection() {
  const activeElement = document.activeElement

  // make sure this is your textarea
  if (activeElement && activeElement.id === 'unique-id') {
    const range = {
      start: activeElement.selectionStart,
      end: activeElement.selectionEnd
    }
    // do something with your range
  }
}

document.addEventListener('selectionchange', handleSelection)

That will run whatever code is in the handleSelection function.

like image 67
shadymoses Avatar answered Sep 21 '22 21:09

shadymoses


You can use the onselect event

object.addEventListener("select", myScript);

https://www.w3schools.com/jsref/event_onselect.asp

like image 41
Macario Avatar answered Sep 19 '22 21:09

Macario