0

The problem is with spaces. Sometimes if the caret is on a space, it ignores the space and finds the position of the last character (that isn't a space). In this demo if you click just right of the letter c it shows caret position as 3. Then click just left of the letter d (one character along) and it still shows caret position as 3. However if you click left of d first, then it shows position 4 (the correct position). If anyone can take a look at my jsFiddle and try this out maybe you can find a solution. Thank you.

NB this code only works in IE.

$('input').click(function(){
  var Sel = document.selection.createRange();
      Sel.moveStart('character', -this.value.length);
      CaretPos = Sel.text.length;
  $('span').text(CaretPos);

});

user2014429
  • 2,497
  • 10
  • 35
  • 49

1 Answers1

0

The selectionStart worked in latest IE, Firefox & Chrome.

$('input').click(function(){
    this.focus();
     /**var Sel = document.selection.createRange();
     Sel.moveStart('character', -inelem.value.length);
     CaretPos = Sel.text.length;*/
    CaretPos = this.selectionStart;   
    $('span').text(CaretPos);
});

But, if you are concerned about supporting older IE versions, you can conditionally invoke createRange over selectionStart. Check this version of fiddle. The doGetCaretPosition is based on this link

Community
  • 1
  • 1
bprasanna
  • 2,423
  • 3
  • 27
  • 39