views:

403

answers:

2

How could can I get the caret position from within an input field.

I have seen a few bits and pieces on google but nothing bullet proof.

Basically something like a Jquery plugin would be ideal so I could simply do

$("#myinput").caretPosition()

I realise there may by other non-jQuery solutions and these would also be brilliant if anyone has any??

+1  A: 

Found this solution. Not jquery based but there is no problem to integrate it to jquery:

/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {

  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus ();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange ();

    // Move selection start to 0 position
    oSel.moveStart ('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;

  // Return results
  return (iCaretPos);
}

From http://flightschool.acylt.com/devnotes/caret-position-woes/

Max
+1  A: 

Nice one, big thanks to Max.

I've wrapped the functionality in his answer into jQuery if anyone wants to use it..

new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var input = $(this).get(0);
        // IE Support
        if (document.selection) {
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            pos = sel.text.length - selLen;
        }
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionStart;

        return pos;
    }
} (jQuery);
MarkB29