Categories
JavaScript Answers

How to get contentEditable caret position with JavaScript?

Spread the love

Sometimes, we want to get contentEditable caret position with JavaScript.

In this article, we’ll look at how to get contentEditable caret position with JavaScript.

How to get contentEditable caret position with JavaScript?

To get contentEditable caret position with JavaScript, we change the selection to start from the beginning and then get the length of the full selected string.

For instance, we write

const cursorPosition = () => {
  const sel = document.getSelection();
  sel.modify("extend", "backward", "paragraphboundary");
  const pos = sel.toString().length;
  if (sel.anchorNode !== undefined) {
    sel.collapseToEnd();
  }

  return pos;
};

to get the selection with getSelection.

Then we move the selection back to the beginning of the input value with

sel.modify("extend", "backward", "paragraphboundary");

And then we get the caret position pos with the length of the selection.

Conclusion

To get contentEditable caret position with JavaScript, we change the selection to start from the beginning and then get the length of the full selected string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *