user3076752
user3076752

Reputation: 91

Caret function doesn't work well if the caret is at the last position

Following the code for get caret position (how many characters there are before the caret in a textarea) in IE8 and less:

function getIEtextareaCaret(el) {
    var start = 0,
    range = el.createTextRange(),
    range2 = document.selection.createRange().duplicate(),
    range2Bookmark = range2.getBookmark();
    range.moveToBookmark(range2Bookmark);
    while (range.moveStart('character' , -1) !== 0) {
    start++;
    }
    return start;
}

It's works well, but if the caret is at the last position (for example, if the textarea contains "abc", the caret is after the c) the function returns a wrong number like 1. How to solve it?

Upvotes: 4

Views: 152

Answers (1)

Lasse
Lasse

Reputation: 1656

This has already been answered in How to get caret position in textarea?.

If you use the code from the answer, you should get the correct offset (Checked in IE8 and Chrome):

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

Plus, this works in other browsers, too.

Upvotes: 1

Related Questions