Cross Browser Javascript Code to Get/Set Caret Position in Textarea/Input

Category: Javascript

Note: In year 2020, this solution still works for textarea/input.

Here is a working snippet of code to get and set the caret position in HTML textarea and textbox. This code works for IE 6, 7, 8, >=9, Firefox, Chrome, Safari and Opera.

Fun Fact: This code is used by Twitter (as per their developer)

function getCaretPosition(ctrl) {
    // IE < 9 Support 
    if (document.selection) {
        ctrl.focus();
        var range = document.selection.createRange();
        var rangelen = range.text.length;
        range.moveStart('character', -ctrl.value.length);
        var start = range.text.length - rangelen;
        return {
            'start': start,
            'end': start + rangelen
        };
    } // IE >=9 and other browsers
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        return {
            'start': ctrl.selectionStart,
            'end': ctrl.selectionEnd
        };
    } else {
        return {
            'start': 0,
            'end': 0
        };
    }
}

function setCaretPosition(ctrl, start, end) {
    // IE >= 9 and other browsers
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(start, end);
    }
    // IE < 9 
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', end);
        range.moveStart('character', start);
        range.select();
    }
}

Here “ctrl” is the Textarea object. You can check it at Get/Set Caret in Textarea Example

Share

84 comments

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

  1. PleaseHelp says:

    Hi guys,

    i writting here after many hours of trying. So i will appreciate any kind of help. I have a big problem with IE.

    When i apply the code above so as it is it work perfect. But if i call function doGetCaretPosition() after blur or keydown or keyup or click on textare it begins to behave “irrationally” showing wrong results (in text but if the cursor is on the end of a text it works correct).

    Any ideas why? Thanks.

  2. Vrinda says:

    Thanks a ton.. this worked wonder… had nightmares to get it done in IE.. this code helped a lot 🙂 thank you..thank you..thank you..thank you..thank you..

  3. fan says:

    It works like a charm. I have tried many codes before you. Yours is super.

    Thanks
    keep up the good work.

  4. Sebastiaan Pol says:

    For getting the correct position in IE10, you need to use the code in the “else if” section (with the “firefox support” comment) in the example. If you want to use the snippet from the example in IE10 change your if statement into the following:

    // IE, but not IE10
    if (document.selection && navigator.appVersion.indexOf(“MSIE 10”) == -1) {
    …..
    }
    // Normal browsers and IE10
    else if (ctrl.selectionStart || ctrl.selectionStart == ‘0’)

  5. Bhavesh says:

    This is not working in IE10. I wants to get current position of cursor in text area. 🙁

  6. Ricardo says:

    “me too”. I see tinyMce uses this kind of function and I was looking to replicate the behaviour in other input fields.

  7. Lekhnath Rijal says:

    Thanks a lot. Very very helpful to me. You saved my huge time, thanks a lot again and again.

  8. vijith says:

    Thanks a lot , it worked for me.

    Thanks\
    vijith

  9. Grey Wolf says:

    It would be nice if you made the line numbering non-selectable and run your code through JSLint. Java bracing is incorrect in JavaScript as it can mess up with the automatic insertion of semi-colons. Sorry but I get sick of seeing crappy Java techniques used in other languages, it is very unnecessary and I see it way to often.

  10. Louys Patrice Bessette says:

    THANKS!!!

    Works fine on the first cut n’paste… No analyzing/debugging/modifying required.
    And for Arun : Works in chrome, no prob.