Categories
JavaScript Answers

How to set caret position at a specific position in contenteditable div with JavaScript?

Spread the love

Sometimes, we want to set caret position at a specific position in contenteditable div with JavaScript.

In this article, we’ll look at how to set caret position at a specific position in contenteditable div with JavaScript.

How to set caret position at a specific position in contenteditable div with JavaScript?

To set caret position at a specific position in contenteditable div with JavaScript, we select the text node that with the text we want the cursor to be at and set the caret position there.

For instance, we write:

<div contenteditable>
  hello world
</div>

to add a contenteditable div.

Then we write:

const node = document.querySelector("div");
node.focus();
const textNode = node.firstChild;
const caret = 10; 
const range = document.createRange();
range.setStart(textNode, caret);
range.setEnd(textNode, caret);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

to select the div with querySelector.

We call focus to focus on the div.

Then we get the text node in the div with node.firstChild.

Next, we call document.createRange to create the selection range.

And then we call setStart and setEnd to set the select range.

Next, we call window.getSelection to get the selection.

And we call removeAllRanges to remove all selection.

And then we call addRange with range to move the cursor.

Conclusion

To set caret position at a specific position in contenteditable div with JavaScript, we select the text node that with the text we want the cursor to be at and set the caret position there.

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 *