Tag Archives: cursor

Web

Get cursor position in textarea or input with JQuery

cursor_pos

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

And here usage example:



getCursorPosition

As the result we’ll see next:
cursor_pos_result

The post was created by originally
http://stackoverflow.com/questions/1891444/how-can-i-get-cursor-position-in-a-textarea/1909997#1909997