SEE BEFORE MARKING DUPLICATE/DOWNVOTING
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);
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With