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
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) {
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. Other than that, the source code is self explanatory.
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.
Thanks ,
Good Article man every helpful
Thanks,
Nice Article, much helpful.
how do i get cursor position when i am using text-angular directive.Any help would be highly obliged.
Thanks a lot.
Its worked for me Fine.
Thanks
Susil
Gud work..!
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.
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..
It works like a charm. I have tried many codes before you. Yours is super.
Thanks
keep up the good work.
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’)
This is not working in IE10. I wants to get current position of cursor in text area. 🙁
“me too”. I see tinyMce uses this kind of function and I was looking to replicate the behaviour in other input fields.
Thanks a lot. Very very helpful to me. You saved my huge time, thanks a lot again and again.
Thanks a lot , it worked for me.
Thanks\
vijith
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.
THANKS!!!
Works fine on the first cut n’paste… No analyzing/debugging/modifying required.
And for Arun : Works in chrome, no prob.
Thanks a lot. Worked for me except in Chrome.Saved my time.
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 ?
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?
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!
not working for a simple text :/
Just what I was looking for…
a) Thanks for this, exactly what I was looking for.
b) Your blog’s tagline is brilliant! I wish I had thought of that.
Thanks for this code,just what i need,This is one of the most useful scripts I’ve ever found.
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.
Can anyone please explain the code….
Great work…could you please tell me How to find the line no and column no of the cursor.
This is one of the most useful scripts I’ve ever found. Thanks a million for keeping this hosted. It was a life saver!
Great script, just what I need. Any thought on how to return the start and end position if a series of characters is selected?
Wonderfull, Thanks
That’s great.
thank´s a lot
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
How could I insert text, tabs and line breaks at the caret position using an on website keyboard?
Thanks
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.
nice
Awesome!!! Tnx
code works! but the AdSense on this page is annoying..
This code works for me. its really gr8. Thanx a lot!!!!
@Alex
You are the best!
@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
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…
el.focus();
var sel = document.selection.createRange();
var sel2 = sel.duplicate();
sel2.moveToElementText(el);
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)) {
sel2.moveStart('character');
caretPos++;
}
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);
}
kindly dont block the freakin content with the ads
Great solution, thx 🙂
i have used the following on a dropdown which is a field on a grid.
if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd(‘character’, pos);
range.moveStart(‘character’, pos);
range.select();
}
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.
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();
prm.add_pageLoaded(pageLoaded);
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));
r.collapse();
r.select();
}
}
else if (browserout === “FF”) {
// Append a space and then backspace to delete it.
var elem = document.getElementById(“TextBox1”);
elem.focus();
elem.setSelectionRange(elem.value.length, elem.value.length);
evt = document.createEvent(“KeyboardEvent”);
evt.initKeyEvent(“keypress”, true, true, null, false, false, false, false, 0, 32);
elem.dispatchEvent(evt);
evt = document.createEvent(“KeyboardEvent”);
evt.initKeyEvent(“keypress”, true, true, null, false, false, false, false, 8, 0);
elem.dispatchEvent(evt);
}
else if (browserout === “Other”) {
if (oTextbox.createTextRange) {
var r = (oTextbox.createTextRange());
r.moveStart(‘character’, (oTextbox.value.length));
r.collapse();
r.select();
}
}
}
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!!!
Has anybody tested this code when the text scrolls out of view? In playing with the example (https://demo.vishalon.net/getset.htm), 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!
Glenn
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…
Clif
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!!!!!!!!!
@Alex
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
VP
how can I paste some text in the current position assigned by those script? Thanks for your help..
Okay, he’s hungry… new, smarter, try:
<input name=”something” id=”something” type=”text” onclick=”getCursorPos(this.id)” onkeyup=”getCursorPos(this.id);” onfocus=”registerTimeField(this);” value=” : “/>
Somone ate my HTML!! New try:
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[control.id]) ? cursorPosSaved[control.id] : 0;
if (window.getSelection) {
cursorPos = control.selectionStart;
} else if (document.selection) {
control.focus();
var oldRange = document.selection.createRange ();
var newRange = oldRange.duplicate();
newRange.expand(‘textedit’);
var cursorPos = -1;
while(newRange.inRange(oldRange)) {
newRange.moveStart(‘character’);
cursorPos++;
if (cursorPos == control.value.length) {
break;
}
}
}
cursorPosSaved[control.id] = cursorPos;
return cursorPos;
}
And the onwhateverstuff:
function registerTimeField(field) {
field.onkeypress = function(e) {
getCursorPos(field.id);
var keyCode = (window.event) ? window.event.keyCode : e.which;
keyChar = String.fromCharCode(keyCode);
debug(‘o’+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) {
getCursorPos(field.id);
var keyCode = (window.event) ? window.event.keyCode : e.which;
debug(keyCode);
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;
}
}
}
HTML:
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[control.id]) ? cursorPosSaved[control.id] : 0;
if (document.selection) {
control.focus();
var oldRange = document.selection.createRange ();
var newRange = oldRange.duplicate();
newRange.expand(‘textedit’);
var cursorPos = -1;
while(newRange.inRange(oldRange)) {
newRange.moveStart(‘character’);
cursorPos++;
if (cursorPos == control.value.length) {
break;
}
}
} else if (control.selectionStart || control.selectionStart == ‘0’) {
cursorPos = control.selectionStart;
}
cursorPosSaved[control.id] = cursorPos;
debug(cursorPos);
return cursorPos;
}
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.
It works! Awesome man, thank you!
with Firefox, I always end up inserting text about 30 chars before the actual caret position! Any hint why?
Its not working with firefox
It is not working fine for ContentEditable Div
How it can be
I thought I’d let you know that your code was useful to me in a way that you probably hadn’t expected. =)
http://my.opera.com/community/forums/topic.dml?id=222466
thank you!
Alex you are awesome! Only your code worked for me!
BTW, damn you IE!!!
just wanted to say thanks, this helped me a lot
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.
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)
{
control.focus();
var Sel = document.selection.createRange ();
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(control);
var CaretPos = -1;
while(Sel2.inRange(Sel))
{
Sel2.moveStart(‘character’);
CaretPos++;
}
}
// Firefox support
else if (control.selectionStart || control.selectionStart == ‘0’)
CaretPos = control.selectionStart;
return (CaretPos);
}
Thanx a lot, that’s what I needed – it works nice with Opera 8.5 as well
ups. I missed this:<SCRIPT LANGUAGE=VBSCRIPT>
option explicit
function newLine(str)
dim nl, r
set nl = new RegExp
nl.global = true
nl.pattern = “\r\n”
set r = nl.Execute(str)
newLine = r.count
set r = nothing
set nl = nothing
end function
</SCRIPT>
I have this:
function getCursorPos(textElement){
var cursorPos = -1;
if (textElement && textElement.createTextRange) {
var range = document.selection.createRange().duplicate();
range.setEndPoint(‘StartToEnd’,range);
var start = document.body.createTextRange();
start.moveToElementText(textElement);
cursorPos = calcBookmark(range.getBookmark())-calcBookmark(start.getBookmark());
var rLen = 0;
do{
var BrLen = rLen;
rLen = newLine(textElement.value.substring(0,cursorPos + rLen + 1));
}while(BrLen!=rLen);
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
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
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.
It’s a shame you didn’t credit the original authors for what is obviously code ripped off from PHPMyAdmin!!!
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….
el.value.substring(iCaretPos).split(‘\n’).length
…it worked perfectly, since I was then only counting line breaks between the caret and the end rather than all of them.
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)
range.select()
}
else // textarea
{
range.collapse(false)
range.move (‘character’, iCaretPos – el.value.length + el.value.split(‘\n’).length – 1)
range.select()
}
}
else if (el.selectionStart || el.selectionStart == ‘0’) // Firefox
{
el.setSelectionRange(iCaretPos, iCaretPos)
}
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.
Thanks for the code.
COOOOOL THE ONE THAT EVER WORKED FOR ME LOTS OF THAAANKS
One of the few javascript examples that actually worked the way I wanted it to. Thanks!
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.
Er, actually I meant line-feeds, not carriage returns.
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?
Thanks adnrey,
My bad. I posted few lines wrong, but now i checked it and it is working with IE.
doesnt work with interenet explorer!