Categories
JavaScript Answers

How to Set the Cursor Position on contentEditable Div with JavaScript?

Spread the love

Sometimes, we want to set the cursor position on a contenteditable div with JavaScript.

In this article, we’ll look at how to set the cursor position on a contenteditable div with JavaScript.

Use the document.creatRange Method

We can use the document.createRange method to create the selection range.

Then we can call addRange on the returned selection object to select the content.

For instance, if we have the following HTML:

<div id="selectable" contenteditable>http://example.com/page.htm</div>

Then we can put a cursor on it by writing:

const el = document.getElementById('selectable');  
const selection = window.getSelection();  
const range = document.createRange();  
selection.removeAllRanges();  
range.selectNodeContents(el);  
range.collapse(false);  
selection.addRange(range);  
el.focus();

We get the div with getElementById .

Then we call window.getSelection to create a selection.

Then we call document.createRange to create the selection range.

Next, we call removeAllRanges to remove any existing selection.

Then we call selectNodeContents with el to apply the selection to the div.

And then we call addRange to select the content.

Finally, we call el.focus() to focus on the element to add the cursor.

Now we should see the cursor at the end of the text.

Conclusion

We can set the cursor position on a contenteditable div with JavaScript browser document.createRange method.

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 *