Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set caret position at a specific position in contenteditable div

Tags:

SEE BEFORE MARKING DUPLICATE/DOWNVOTING

  1. The contenteditable div will not have child elements
  2. I do not want to set the position at the end of the div
  3. I do not want a cross-browser solution, only Chrome support required
  4. Only vanilla JS, no libraries.

I have seen many many solutions. Many by Tim Down, and others. But none does work. I have seen window.getSelection, .addRange etc. but don't see how they apply here.

Here's a jsfiddle.

(Tried) Code:

var node = document.querySelector("div");
node.focus();
var caret = 10; // insert caret after the 10th character say
var range = document.createRange();
range.setStart(node, caret);
range.setEnd(node, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
like image 841
Gaurang Tandon Avatar asked Jun 09 '14 07:06

Gaurang Tandon


People also ask

How do you set a caret position?

The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning.

How do you get caret position within Contenteditable div with HTML child elements?

So, when the user is typing text, I can, at any point, know the caret position within the contentEditable element. Look at its position in the text. Then, look up the last occurance of '@' before that position.

How do you move the cursor to the end of Contenteditable entity?

selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point. false means collapse to end rather than the start selection = window. getSelection();//get the selection object (allows you to change selection) selection.


1 Answers

You need to position the caret within the text node inside your element, not the element itself. Assuming your HTML looks something like <div contenteditable="true">Some text</div>, using the firstChild property of the element will get the text node.

Updated jsFiddle:

http://jsfiddle.net/xgz6L/8/

Code:

var node = document.querySelector("div");
node.focus();
var textNode = node.firstChild;
var caret = 10; // insert caret after the 10th character say
var range = document.createRange();
range.setStart(textNode, caret);
range.setEnd(textNode, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
like image 181
Tim Down Avatar answered Sep 21 '22 12:09

Tim Down