Reputation: 367
I have following html:
<div id="content" contenteditable="true" style="font-family: Helvetica;">
Some text
<div id="cursor" contenteditable="true"></div>
Some other text.
</div>
Now I want to set cursor after Some text (exactly in #cursor
). I tried both way:
$('#cursor').focus();
document.getElementById('#cursor').focus();
but it didn't work. Is there any way to do this?
Upvotes: 1
Views: 2308
Reputation: 318182
#content
is the outer editable element, so you'll need to focus that, and move the caret inside #cursor
, but as #cursor
has no content, there is nothing to target for a selection. A solution would be to add some content to target, like a textNode, move the caret, and then remove the content, like so:
var el = document.getElementById("content"),
el2 = document.getElementById("cursor"),
range = document.createRange(),
sel = window.getSelection();
el2.innerHTML="temp";
var t = el2.childNodes[0];
range.setStartBefore(t);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
el2.innerHTML = "";
Upvotes: 2