Reacting to selection changes in an HTML textarea
Asked Answered
A

2

12

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.

Allout answered 9/10, 2017 at 16:58 Comment(0)
S
15

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.

Selfcontrol answered 8/10, 2019 at 22:38 Comment(3)
Sounds promising! Will test and get back.Allout
Works in Chrome, it seems I need to add the event listener on/to the window object, not the document. Thanks! (BTW, suggested link fix.)Allout
Well what do you know, there seems to be a bug or two in Chrome. I discovered a couple of things that don't seem to trigger selection change event: 1) backspace (empty selection or collapsing), 2) collapsing undo or redo. No issue in Safari though.Allout
S
3

You can use the onselect event:

object.addEventListener("select", myScript);

Swoon answered 14/3, 2019 at 23:6 Comment(1)
Yes, but it only goes part way: AFAICT you don't get selection changes during mouse drag, only when finished selecting or mouseup, and you don't get called back when the selection is collapsed. (Maybe I should edit the question to clarify.)Allout

© 2022 - 2024 — McMap. All rights reserved.