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

Category: Javascript

Note: In year 2021, 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, Edge, Chrome, Safari, Firefox and Opera.

Interactive Example

from to

How to set caret position

Type the number where you want to set the caret position and click on “Set Position” button.

How to set selection

Type the starting character number and end character number. Then click on “Set Selection” button to set selection.

How to get caret position or selection

Click on “Get Position/Selection”. If there is no selection (i.e. selection is collapsed), you will see only single value. This value represents current caret position. If there is a selection, you will see start and end position for selection.

Browser Caveats

Some browser considers new line character as single character whereas some browser handles new line character as two separate characters.

Fun Fact

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

JavaScript Source Code

function getCaretPosition(ctrl) {
    // IE < 9 Support 
    if (document.selection) {
        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.setSelectionRange(start, end);
    // IE < 9 
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.moveEnd('character', end);
        range.moveStart('character', start);;

Here ctrl is the Textarea object. Other than that, the source code is self explanatory.



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

  1. Scott says:

    With my JavaScript/C# application, a user can enter multiple SQL statements in a textarea, select one, and submit the form to execute it. The content of the textarea persists from post to post (which is what I want), but I also wanted the selection to persist from post to post. After several hours of searching for a solution, this code did the trick. I pass the start and finish positions of the selected text in hidden form fields and use them to set the selection range with your function on page load. Excellent.

  2. Prakash says:

    Thanks ,
    Good Article man every helpful

  3. Manas says:


    Nice Article, much helpful.

  4. Abhay Mishra says:

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

  5. Susil Kumar Sethi says:

    Thanks a lot.
    Its worked for me Fine.


  6. Pushpa says:

    Gud work..!

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

  8. 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..

  9. fan says:

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

    keep up the good work.

  10. 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’)

  11. Bhavesh says:

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

  12. Ricardo says:

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

  13. Lekhnath Rijal says:

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

  14. vijith says:

    Thanks a lot , it worked for me.


  15. 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.

  16. Louys Patrice Bessette says:


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

  17. Arun says:

    Thanks a lot. Worked for me except in Chrome.Saved my time.

  18. DenisStarbank says:

    Works fine for me with IE and Mozilla, on textboxes which is what I want – I’ve tried a few other claimed caret finders, setters, but ran into problems with them – so many thanks for this one. Has anyone tried this with Chrome, Safari, Android ?

  19. Carl says:

    It doesn’t work if textarea is not the first element inside html body. I wrote ‘123456789’ and click between 3 and 4 and alert says the position is 6 (should be 3). I’m working on IE9. It’s a IE bug? what’s wrong?

  20. Leo says:

    Getting of caret position for textarea returns a false result on IE. Paste into the textarea any text and place the caret at random place somewhere in the middle( absolutely not at the beginning). Then you will notice that the result being return is totally false. However, that can be fixed by setting the caret position at the beginning via the second function and re-run the first function. In this way, one may get the correct position!

  21. yvan says:

    not working for a simple text :/

  22. Striketes says:

    Just what I was looking for…

  23. Benjie says:

    a) Thanks for this, exactly what I was looking for.
    b) Your blog’s tagline is brilliant! I wish I had thought of that.

  24. Prajakta Tapadiya says:

    Thanks for this code,just what i need,This is one of the most useful scripts I’ve ever found.

  25. Bibick says:

    It’s does’t work in Chrome. It set caret position, but when element lost focus, caret return to the begin. Haw make it work in chrome? Sorry for my english.

  26. Sameer says:

    Can anyone please explain the code….

  27. Manoj says:

    Great work…could you please tell me How to find the line no and column no of the cursor.

  28. Ben says:

    This is one of the most useful scripts I’ve ever found. Thanks a million for keeping this hosted. It was a life saver!

  29. Dan says:

    Great script, just what I need. Any thought on how to return the start and end position if a series of characters is selected?

  30. Pradeep says:

    Wonderfull, Thanks

  31. David says:

    That’s great.

  32. Peter says:

    thank´s a lot

  33. Steve says:

    Thanks for this. I’m struggling with it a bit. I’ve got the added complexity that I need to setCaretPosition in a different frame. The application is that by clicking on a text box in Frame A causes a page to load in Frame B but then I need the caret to stay in the same place in Frame A. Firefox seems to be smart enough to do this without any code but I can’t get it to work in IE. What I’ve tried is getting the position in Frame A and passing both it and the ID name of the field that I need the caret positioned in. Then in FRAME B’s script I tried onLoad=setCaretPosition(ID,pos) setting the ctrl name as: var ctrl = parent.frames[‘frame_A_name’].document.getElementById(ID); in setCaretPos(). I’ve verified that the ID and pos is passing correctly but doesn’t seem to be generating the right element id or something as the caret never appears. Frames always mess me up. Thanks for any help

  34. Alec says:

    How could I insert text, tabs and line breaks at the caret position using an on website keyboard?

  35. Pedro says:


  36. Gowri says:

    Hi Vishal,
    Thank u for your solution. I was searching for a long time and was banging my hang for this problem. Your solution worked like a swift. Thank u once again.

  37. r says:


  38. teamwork says:

    Awesome!!! Tnx

  39. asdf says:

    code works! but the AdSense on this page is annoying..

  40. Jayesh Trivedi says:

    This code works for me. its really gr8. Thanx a lot!!!!

  41. Lucas says:

    You are the best!

  42. Simon Sanderson says:

    @Alex this posting works just fantastic Alex August 19th, 2007 at 03:35 #18. I wasted about 3 days trying to understand othermechanisms to get around problems (some of) associated with IE V6.
    This was the only example of code that behaved the same in both FF and IE for me :-))
    Thanks to you Alex

  43. Haig says:

    Hey everyone. This conversation has really helped point me in the right direction. I was having major issues with IE document selection. I tried many solutions, and found Alex’s to be the best. However, the code is really inefficient and starts to show when you’re working with a good amount of text in a textarea. I therefore made a few enhancements to Alex’s code to prevent looping through every character from the beginning of the textarea everytime you need to get cursor/selection positions. I also added the code to return the endpoint as well as the startpoint for selection range. I tested this in on FF3.5/Ubuntu/Win, IE8/Win, Chrome 4.1/Win, Chrome 5/Ubuntu, Safari4/Win, Opera10.53/Win, I hope this helps someone out. Cheers!

    var textArea = $(‘myTextArea’);
    var getPos = function() {setTimeout(“debugOutput();”, 1);};
    var pos = 0;

    textArea.onkeydown = getPos;

    function debugOutput() {
    var sel = getCursorPosition(textArea, pos);
    pos = sel.start;
    $(‘lblStart’).innerHTML = sel.start;
    $(‘lblEnd’).innerHTML = sel.end;

    function getCursorPosition(el, pos) {
    if (document.selection) { // IE…
    var sel = document.selection.createRange();
    var sel2 = sel.duplicate();

    if(sel.text.length > 1) {
    pos = pos – sel.text.length;
    if(pos < 0) {
    pos = 0;

    var caretPos = -1 + pos;
    sel2.moveStart('character', pos);

    while(sel2.inRange(sel)) {
    var selStr = sel.text.replace(/\r/g, "");
    return {start: caretPos, end: selStr.length + caretPos};
    }else if (el.selectionStart || el.selectionStart == 0) { //Most other browsers
    return {start: el.selectionStart, end: el.selectionEnd};

    function $(el) {
    return document.getElementById(el);

  44. noads says:

    kindly dont block the freakin content with the ads

  45. killerbees19 says:

    Great solution, thx 🙂

  46. miller says:

    i have used the following on a dropdown which is a field on a grid.
    if (ctrl.createTextRange) {
    var range = ctrl.createTextRange();
    range.moveEnd(‘character’, pos);
    range.moveStart(‘character’, pos);;
    it selects the data fine. but the the method the focus doesn’t move from the dropdown. so, when i select the row on the grid, the dropdown always gets the focus. how can I set the focus out of the dropdown once the above code is run.
    Thank you.

  47. Glenn says:

    I finally found/created a workable answer to the issue of not scrolling in Firefox. Specifically, I have a an AJAX updatepanel with dropdown list and an “insert” button. The user selects a value from the dropdown list, clicks the Insert button, and the value is appended to the value in the textbox. IE was easy, but FF was a nightmare. The solution was in combining many parts of multiple answers found on the web (i.s no one solution seemed to work with Ajax. I am not a “Javascript” guy, so there is probably room for lots of improvement – but it works for me. I am primarily concerned with FF and IE, but it could easily be modded for other browsers. Here is the code:

    // Added for Ajax/Updatepanel
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    function pageLoaded(sender, args) {
    var oTextbox = document.getElementById(”);
    var browserout = findBrowser();
    if (browserout === “IE”) {
    if (oTextbox.createTextRange) {
    var r = (oTextbox.createTextRange());
    r.moveStart(‘character’, (oTextbox.value.length));
    else if (browserout === “FF”) {
    // Append a space and then backspace to delete it.
    var elem = document.getElementById(“TextBox1”);
    elem.setSelectionRange(elem.value.length, elem.value.length);
    evt = document.createEvent(“KeyboardEvent”);
    evt.initKeyEvent(“keypress”, true, true, null, false, false, false, false, 0, 32);
    evt = document.createEvent(“KeyboardEvent”);
    evt.initKeyEvent(“keypress”, true, true, null, false, false, false, false, 8, 0);
    else if (browserout === “Other”) {
    if (oTextbox.createTextRange) {
    var r = (oTextbox.createTextRange());
    r.moveStart(‘character’, (oTextbox.value.length));
    function findBrowser() {
    var browser = {
    ‘name’: navigator.appName,
    ‘version’: navigator.appVersion,
    ‘userAgent’: navigator.userAgent,

    // Functions returning true or false
    ‘isFF’: function() { return !(this.userAgent.indexOf(“Firefox”) == -1); },
    ‘isIE’: function() { return !(this.userAgent.indexOf(“MSIE”) == -1); },
    ‘isIE6’: function() { return !(this.userAgent.indexOf(“MSIE 6”) == -1); },
    ‘isIE7’: function() { return !(this.userAgent.indexOf(“MSIE 7”) == -1); },
    ‘isOpera’: function() { return !(this.userAgent.indexOf(“Opera”) == -1); },
    ‘isSafari’: function() { return !(this.userAgent.indexOf(“Safari”) == -1); }
    if (browser.isFF() == 1) { return(“FF”); }
    else if (browser.isIE() == 1) { return (“IE”); }
    else { return (“Other”); }

    Special thanks to all of the folks that have posted the parts I used to aggregate this. Extra special thanks to Saul on Stackoverflow for the “Keypress” idea!!!

  48. Glenn says:

    Has anybody tested this code when the text scrolls out of view? In playing with the example (, with IE 7, the cursor will go to the desired spot AND will scroll to the appropriate view. With Firefox (3.6), the cursor goes to correct spot BUT the scroll view does not change. Obviously, this would generate some negative feedback from users where text is being appended and they are forced to manually scroll to the bottom each time. Does anybody know of a fix for this? Other than this, the code seems to work really great!


  49. Clif says:

    I Found out that IE counts caret position using only 1 character for Carriage Return / Line Feed even though the textarea.innerText contains 2 characters.

    So when Counting Caret Position either for setting or retrieving, you should count text by deleting either the CR or LF in a scratch work area:

    data = mytext.innerText.replace(/\r/g,”);
    pos = data.indexOf(‘Hello World’);

    This is only for IE, I hope this helps…

  50. sara says:

    hellow please help me :this code dont work in firefox whyyyyyyyy?
    function number_textbox()
    if (window.event.keycode57)
    {alert(“لطفاًعدد وارد نماييد”)
    window.event.cancelBubble = true
    window.event.returnValue = false;

    thanks a lot!!!!!!!!!

  51. phuong says:

    hi Alex
    i had apply your getcareposition function it work fine, but seem to be my problem come from setcareposition function i hand used setcareposition (18) after that i use getcareposition and the result is 20
    any idea from you, many thank for your help

  52. bayu says:

    how can I paste some text in the current position assigned by those script? Thanks for your help..

  53. Pal says:

    Okay, he’s hungry… new, smarter, try:

    <input name=”something” id=”something” type=”text” onclick=”getCursorPos(” onkeyup=”getCursorPos(;” onfocus=”registerTimeField(this);” value=” : “/>

  54. Pal says:

    Somone ate my HTML!! New try:

  55. Pal says:

    Okay, that didn’t work in Opera, since Opera supports both kind of objects, but it doesn’t support the expand method. Sigh.

    Anyway, it supports the FF/Safari stuff, so changing the order of the methods solved that problem.

    I also had to fix my onwhataver-stuff, since IE/FF/Safari fires onkeydown for the arrow keys (which change the cursor position), but Opera does not. Opera fired onkeypress but not onkeydown. So, I hade to build make the function detect itself and put in both onwhatevers… sigh again!

    Anyway, here’s the Opera comatible code:

    function getCursorPos(id) {
    control = document.getElementById(id);
    var cursorPos = (cursorPosSaved[]) ? cursorPosSaved[] : 0;
    if (window.getSelection) {
    cursorPos = control.selectionStart;
    } else if (document.selection) {
    var oldRange = document.selection.createRange ();
    var newRange = oldRange.duplicate();
    var cursorPos = -1;
    while(newRange.inRange(oldRange)) {
    if (cursorPos == control.value.length) {
    cursorPosSaved[] = cursorPos;
    return cursorPos;

    And the onwhateverstuff:

    function registerTimeField(field) {
    field.onkeypress = function(e) {
    var keyCode = (window.event) ? window.event.keyCode : e.which;
    keyChar = String.fromCharCode(keyCode);
    if (keyCode == 8 || keyCode == 0 || keyCode == 37 || keyCode == 39 || (keyCode > 115 && keyCode < 124) || keyCode == 45 || keyCode == 46) {
    return true;
    } else if (keyCode == 38 || keyCode == 40) {
    (keyCode == 38) ? do arrow-up-stuff : do arrow-down-stuff ;
    } else {
    return (detect-validation-error-stuff) ? false : true;
    field.onkeydown = function(e) {
    var keyCode = (window.event) ? window.event.keyCode : e.which;
    if (keyCode == 38 || keyCode == 40) {
    (keyCode == 38) ? do arrow-up-stuff : do arrow-down-stuff;
    (e) ? e.stopPropagation : window.event.cancelBubble = true;
    return false;
    } else {
    return true;


  56. Pal says:

    Since this thread, and especially Alex version, helped me solve my problem, I thought I’d paste it here to solve other people’s problems.

    Alex version worked for FF, IE and Safari for Textareas and for FF and Safari for input text. But it didn’t work at all for IE input texts (threw “Invalid argument” at “moveToElementText(control)”).

    So, I fixed that problem by doing “expand(‘textedit’)” instead. Now it worked in all sex occasions, except when the cursor ended up dead last in the input text. It made IE freeze inside the “moving selection one step loop”. So, I added a maximum bail-out value at the length of the text. Then it finally worked for IE, FF and Safari in both text areas and input texts!

    I also added a global variable to keep track of the position when out of focus in IE (the other ones did that by themselves).

    Some variables have new names, and I have no idea what this forum will do to qoutes and stuff, but here goes:

    var cursorPosSaved = new Array();

    function getCursorPos(id) {
    control = document.getElementById(id);
    var cursorPos = (cursorPosSaved[]) ? cursorPosSaved[] : 0;
    if (document.selection) {
    var oldRange = document.selection.createRange ();
    var newRange = oldRange.duplicate();
    var cursorPos = -1;
    while(newRange.inRange(oldRange)) {
    if (cursorPos == control.value.length) {
    } else if (control.selectionStart || control.selectionStart == ‘0’) {
    cursorPos = control.selectionStart;
    cursorPosSaved[] = cursorPos;
    return cursorPos;

  57. AndyT says:

    The original script works only on textarea without carriage return. The position is off by one for each Enter hit. Is there a fix for this? I’m trying to implement an autofill script in the textarea and need to find the exact position.

  58. Michal Hantl says:

    It works! Awesome man, thank you!

  59. zab says:

    with Firefox, I always end up inserting text about 30 chars before the actual caret position! Any hint why?

  60. ledaker says:

    Its not working with firefox

  61. ramesh says:

    It is not working fine for ContentEditable Div
    How it can be

  62. smartphone freeware says:

    thank you!

  63. dumbo says:

    Alex you are awesome! Only your code worked for me!

    BTW, damn you IE!!!

  64. John S says:

    just wanted to say thanks, this helped me a lot

  65. p says:

    This is just great! I’d been trying out all sorts of things which were half-working. This is simple and works well across browsers.

  66. Alex says:

    OK, I get it – it does not work in my […]ing MSIE.

    Here is slightly modified code compatible to IE 6.0 and Opera:

    function GetCaretPosition(control)
    var CaretPos = 0;
    // IE Support
    if (document.selection)
    var Sel = document.selection.createRange ();
    var Sel2 = Sel.duplicate();
    var CaretPos = -1;

    // Firefox support

    else if (control.selectionStart || control.selectionStart == ‘0’)
    CaretPos = control.selectionStart;

    return (CaretPos);


  67. Alex says:

    Thanx a lot, that’s what I needed – it works nice with Opera 8.5 as well

  68. Alejandro says:

    ups. I missed this:<SCRIPT LANGUAGE=VBSCRIPT>
    option explicit
    function newLine(str)
    dim nl, r
    set nl = new RegExp = true
    nl.pattern = “\r\n”
    set r = nl.Execute(str)
    newLine = r.count
    set r = nothing
    set nl = nothing
    end function

  69. Alejandro says:

    I have this:
    function getCursorPos(textElement){
    var cursorPos = -1;
    if (textElement && textElement.createTextRange) {
    var range = document.selection.createRange().duplicate();
    var start = document.body.createTextRange();
    cursorPos = calcBookmark(range.getBookmark())-calcBookmark(start.getBookmark());
    var rLen = 0;
    var BrLen = rLen;
    rLen = newLine(textElement.value.substring(0,cursorPos + rLen + 1));
    cursorPos += rLen;
    return cursorPos;
    function calcBookmark(bk){
    return (bk.charCodeAt(0)-1)+(bk.charCodeAt(3)-1)*65536+(bk.charCodeAt(2)-1);
    It work’s for textarea in IE

  70. rajesh says:

    i am developing a web page in which i need to enter a text into a textbox at the cursor position, on button click from another text box.

    Please help me if know how it is to be done

  71. Ric,

    When I wanted this functionality, I tried google and got code from some website (surely not PHPMyAdmin website). I tried that code and did not workout. Then from that code, using trial and error method (I am NOT javascript programmer), I got this code. I dont know if it is “ripped off” version of PHPMyAdmin or not.

  72. Ric says:

    It’s a shame you didn’t credit the original authors for what is obviously code ripped off from PHPMyAdmin!!!

  73. drew says:

    Hi Peder – this was helpful but I did find it only worked correctly with the caret in the last line.

    By changing the split part to….


    …it worked perfectly, since I was then only counting line breaks between the caret and the end rather than all of them.

  74. Peder says:

    Seems like the setCaretPosition function got truncated in my prior posting:

    function setCaretPosition (el, iCaretPos)
    if (document.selection) // IE
    var range

    range = document.selection.createRange()

    if (el.type == ‘text’) // textbox
    range.moveStart (‘character’, -el.value.length)
    range.moveEnd (‘character’, -el.value.length)
    range.moveStart (‘character’, iCaretPos)
    else // textarea
    range.move (‘character’, iCaretPos – el.value.length + el.value.split(‘\n’).length – 1)
    else if (el.selectionStart || el.selectionStart == ‘0’) // Firefox
    el.setSelectionRange(iCaretPos, iCaretPos)

  75. Peder says:

    The code above didn’t work for me on IE. The following seems to fix the problem. Thanks for helping me get in the right direction.

    function getCaretPosition (el)
    var iCaretPos = 0

    if (document.selection) // IE hack
    if (el.type == ‘text’) // textbox
    var selectionRange = document.selection.createRange()
    selectionRange.moveStart (‘word’, -el.value.length)
    iCaretPos = selectionRange.text.length
    else // textarea
    iCaretPos = Math.abs(document.selection.createRange().moveStart(“character”, -1000000)) – 193;
    else if (el.selectionStart || el.selectionStart == ‘0’) // Firefox
    iCaretPos = el.selectionStart

    return iCaretPos;

    function setCaretPosition (el, iCaretPos)
    if (document.

  76. Thay says:

    Thanks for the code.

  77. VICTOR says:


  78. Phil says:

    One of the few javascript examples that actually worked the way I wanted it to. Thanks!

  79. Chris says:

    After playing with this more I found that it does not work in IE. If you have more than one control, or text on the page it simply will not work.

    The problem is Sel.moveStart (‘character’, -ctrl.value.length); which will move the selection to incorporate data not in the current control if there is any. So the length comes out all wrong except for the first item on the page.

  80. Chris says:

    Er, actually I meant line-feeds, not carriage returns.

  81. Chris says:

    Nice simple information I have been looking for. It seems there are many (mostly too complex) ways of doing this in IE.

    However, doGetCaretPosition does not work in IE if there are carriage returns in the textarea. I’m not sure exactly why but IE must remove them from the selection or something. The returned caret position will be off by one for every carriage return in the textarea prior to the caret position.

    Any ideas on how to fix this?

  82. Thanks adnrey,

    My bad. I posted few lines wrong, but now i checked it and it is working with IE.

  83. adnrey says:

    doesnt work with interenet explorer!