Skip to content
Advertisement

Reacting to selection changes in an HTML textarea

How can I get, for an HTML textarea element, 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.)

I can’t find it in HTML documentation or on Stack Overflow.

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 it is also not really good.

Advertisement

Answer

You want 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.

Advertisement