Get cursor position in textarea or input with JQuery


The next snippet is a JQuery function helps to obtain the posiion of cursor in any HTML input element:

    (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) {
                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;

And here usage example:


As the result we’ll see next:

The post was created by originally

  • Marc Davenne

    this is not working… always gving the last position (quite the size of the text). But the real position of the cursor… no.. well for me with IE8

  • Melroy van den Berg

    Nobody uses IE