'javascript – execute when textarea caret is moved

I have textarea and I want to change text that says what character is after the caret (cursor).

<textarea id="text"></textarea>
<br/>
Character after the caret: <span id="char"></span>

I know how to get caret position. The problem is I don't know what event is invoked when users movet the caret (by typing, pressing arrow keys, clicking, pasting text, cutting text, …).



Solution 1:[1]

There is an event for when the selection changes, selectionchange.

The selectionchange event is a global event, so listeners can be added on any element, although there is an experimental feature where event listeners on input elements and textarea elements only listen to changes in selection within that element. The experimental version is currently only supported in Firefox.

The selection can then be accessed through getSelection(). In a few browsers this will return undefined if the selection is inside an input or textarea element, so if getSelection() returns undefined, selectionStart and selectionEnd would work.

Example of the global selectionchange event:

let counter = 0;

document.addEventListener("selectionchange", function () {
  document.querySelector("#counter").textContent = ++counter;
})
<textarea>sample text</textarea>
<p>sample text in a paragraph</p>
<p contenteditable>a paragraph you can edit</p>

<p><code>selectionchange</code> events: <span id="counter">0</span></p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jiwopene