Subscribe For Free Updates!

We'll not spam mate! We promise.

May 4, 2013

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

TechniqZone Socializer Widget
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

2 comments:

  1. AnonymousMay 14, 2013

    i need this code in javascript. any one help?

    ReplyDelete
  2. 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.

    ReplyDelete