Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, …).

like image 651
jiwopene Avatar asked Jan 01 '19 22:01

jiwopene


1 Answers

I don't think there's a built-in event to check that, but you can use a combination of keypress, mousedown, and the other events that can trigger a caret position change, then check for changes to the textarea's selectionStart (which indicates caret position):

const textarea = document.querySelector('textarea');
textarea.addEventListener('keypress', checkcaret); // Every character written
textarea.addEventListener('mousedown', checkcaret); // Click down
textarea.addEventListener('touchstart', checkcaret); // Mobile
textarea.addEventListener('input', checkcaret); // Other input events
textarea.addEventListener('paste', checkcaret); // Clipboard actions
textarea.addEventListener('cut', checkcaret);
textarea.addEventListener('mousemove', checkcaret); // Selection, dragging text
textarea.addEventListener('select', checkcaret); // Some browsers support this event
textarea.addEventListener('selectstart', checkcaret); // Some browsers support this event

let pos = 0;
function checkcaret() {
  const newPos = textarea.selectionStart;
  if (newPos !== pos) {
    console.log('change to ' + newPos);
    pos = newPos;
  }
}
<textarea></textarea>
like image 59
CertainPerformance Avatar answered Oct 06 '22 08:10

CertainPerformance