Stephen Sorensen
Stephen Sorensen

Reputation: 11925

Is there an event that will tell me when a textarea's selection/cursor position changes?

I'm using the selectionStart, selectionEnd, and selectionPosition properties for a textarea I'm manipulating, but I need an event that will tell me when these values change?

I found the document selectionchange event, but that's not quite what I want. It fires on the document directly and does so when any selection in the document changes (too much). I want something scoped to the textarea.

Does such an event exist?

If it doesn't, I'll be forced to use either the document's selectionchange event or a combination of keyup/mouseup on the textarea with some extra conditions to make sure it actually changed.

Upvotes: 1

Views: 406

Answers (2)

Rodrigo Borba
Rodrigo Borba

Reputation: 1474

You can track onKeyDown event inside your input and run it for every time the event is fired

Upvotes: 0

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18909

Seems you cannot fire a selection change event on the element, so we will need to add to the document.

The selection is only ever happening once at a given time, so really no issue listening to it and filtering as needed. Remember all events on elements are propagating up to document anyway, we just not listening to them all.

Added a snippet to demo.

Snippet:

const target = document.querySelector('#content');

document.addEventListener('selectionchange', checkSelection);

function checkSelection(e) {
  if(document.activeElement !== target) {
    return;
  }
  
  console.log(document.getSelection().toString());
}
<textarea id="content">
  How do I check where the cursor is?
</textarea>

<textarea id="notme">
  Not this content please
</textarea>

Upvotes: 3

Related Questions