0

How do I set the cursor between the a and the b below?

<div contenteditable = true id = "test">
  abcdefg
</div>

I have tried to play with ranges, but nothing is working for me. The below code selects the entire text, and there is no cursor. (This code is for Chrome)

sel =  window.getSelection();
range =  document.createRange();
node = document.getElementById("test");
range.setStart(node, 0);
range.setEnd(node, 1);
sel.addRange(range);
user984003
  • 28,050
  • 64
  • 189
  • 285
  • check these http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area – jmingov May 24 '13 at 18:18
  • That works for a textarea, but not for contenteditable. I created a jsfiddle: http://jsfiddle.net/5a9uD/ (uncomment the js line for textarea to see it working there ) – user984003 May 24 '13 at 18:24

1 Answers1

0

This should work:

function setSelectionRange(aNode, aOffset) {

    aNode.focus();

    var sel     = window.getSelection(),
        range   = sel.getRangeAt(0);

    range.collapse(true);
    range.setStart(aNode.childNodes[0], aOffset),

    sel.removeAllRanges();
    sel.addRange(range);
}

setSelectionRange(document.getElementById("test"), 1);

http://jsfiddle.net/5a9uD/1/

If you look to MDN documentation https://developer.mozilla.org/en-US/docs/Web/API/range.setStart you will see that this interface use a node not an element.

Mircea
  • 11,373
  • 26
  • 64
  • 95
  • Here is the answer for a slightly more advanced example: http://stackoverflow.com/questions/17358651/javascript-contenteditable-set-cursor-at-character-offset – user984003 Jun 28 '13 at 07:01