Get cursor position in a textarea – Jquery

Get cursor position in a textarea – Jquery:

The following code is used to get the cursor point in textarea. if you change the id of textarea with particular div id then you can get the cursor points within the div.

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

the bellow code is for set textarea id to call the above function.

$(“#myTextBoxSelector”).getCursorPosition();

2 comments

  1. Thanks
    I'm making a dual textbox editing thing, where i would like arrow keys to move focus between textboxes, when cursor position is first or last.
    This was the simplest solution I have found.

Leave a Reply

Your email address will not be published. Required fields are marked *