Cross browser Javascript code to get/set caret position in textarea/input

Category: Javascript

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. If you are looking for code snippet that works for content editable div or iframe with design mode = on, please contact me.

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. Manas says:

    Thanks,

    Nice Article, much helpful.

  2. Abhay Mishra says:

    how do i get cursor position when i am using text-angular directive.Any help would be highly obliged.

  3. Susil Kumar Sethi says:

    Thanks a lot.
    Its worked for me Fine.

    Thanks
    Susil

  4. Pushpa says:

    Gud work..!