Cursor position in a textarea (character index, not x/y coordinates)

kmunky picture kmunky · Dec 12, 2009 · Viewed 85.1k times · Source

How can I get the caret's position in a textarea using jQuery? I'm looking for the cursor's offset from the start of the text, not for the (x, y) position.

Answer

Ryan picture Ryan · Dec 15, 2009

Modified BojanG's solution to work with jQuery. Tested in Chrome, FF, and IE.

(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

Basically, to use it on a text box, do the following:

$("#myTextBoxSelector").getCursorPosition();