2

The code below is what I use now, just to set the cursor position to the tail of span

var node = document.getElementById("span_first");
var range = document.createRange();  
range.setStartAfter(node);
var sel = window.getSelection();
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);

http://jsfiddle.net/vXnCM/3837/

But I want to set the cursor position at any place in the span, how can I do?

Thanks you.

David Tsui
  • 53
  • 1
  • 8

2 Answers2

6

You can do it like this:

function setCaret() {
   var element = document.getElementById("input");
   var range = document.createRange();  
   var node;   
   node = document.getElementById("first");  
   range.setStart(node.childNodes[0], 1);  <-- sets the location 
   var sel = window.getSelection();
   range.collapse(true);
   sel.removeAllRanges();
   sel.addRange(range);
   element.focus();    
}

node.childNodes[] pertains to which line you want to set the cursor on and the next number is the location on that line. In this example is moves to space 1 line 0 (line 1 really). So if you change those values to variables and put them as parameters in your function you could specify where.

floor
  • 1,519
  • 11
  • 24
0

You might want to use SetTimeout if the selection happens in response to event (e.g. focus), otherwise it might not work (e.g. moving the cursor to end):

  moveCursorToEnd(el){
    if(el.innerText && document.createRange)
    {
      window.setTimeout(() =>
        {
          let selection = document.getSelection();
          let range = document.createRange();

          range.setStart(el.childNodes[0],el.innerText.length);
          range.collapse(true);
          selection.removeAllRanges();
          selection.addRange(range);
        }
      ,1);
    }
  }
Maxim Saplin
  • 4,115
  • 38
  • 29