AnApprentice
AnApprentice

Reputation: 110950

Given a contentEditable Div how to set the cursor to a specific position?

Given a contentEditable div like so:

<div contenteditable="true">Here is some text, hello world.</div>

How can I set the cursor at position 6, right after the s in is?

I've been trying to use:

savedRange = window.getSelection().getRangeAt(0);

And then modify the values like so:

savedRange.startOffset = 6
savedRange.endOffset = 6

But that isn't updating the savedRange.

Any ideas how I can get the cursor/caret in the div? thanks

Upvotes: 3

Views: 1139

Answers (1)

Tim Down
Tim Down

Reputation: 324507

That's position 7. Anyway, here's how, assuming you give your editable <div> an id of "myDiv". Note this won't work in IE < 9, which has a completely different range and selection API.

if (window.getSelection) {
    var sel = window.getSelection();
    var textNode = document.getElementById("myDiv").firstChild;
    var range = document.createRange();
    range.setStart(textNode, 7);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}

Upvotes: 4

Related Questions