1

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?

Linus Caldwell
  • 10,908
  • 12
  • 46
  • 58
cat
  • 357
  • 1
  • 5
  • 14

1 Answers1

2

#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 = "";

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388