Is it possible to programmatically determine the caret position in the <input type = text> element?
Assuming a regular text field <input type=text> with data in it.
Is it possible to detect (via JavaScript) the position of the text cursor inside this text box?
I can detect ARROW LEFT or ARROW RIGHT keydown, but how to locate the cursor?
Why do I need it:
I have a dynamic text box here: http://vidasp.net/tinydemos/dynamic-textbox.html
It works fine, however there are two scenarios that I would like to fix:
- when the cursor is at the beginning of the text field and the user presses the BACKSPACE button
- when the cursor is at the end of the text field and the user presses DELETE
(In both cases, the text box should contain data for the observed effect.)
I worked a lot on this. In all major browsers (including IE 6), the text <input> and <textarea> works in all major browsers and will work in all situations, including in the presence of leading and trailing spaces (in which many solutions, including tools, fall ) There are some prerequisites for this code in this question: IE document.selection.createRange does not include leading or trailing blank lines
You can also get the following as part of a jQuery input / text box input plugin that I haven't documented yet: http://code.google.com/p/rangyinputs/
function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end }; } var el = document.getElementById("your_input"); var sel = getInputSelection(el); alert(sel.start + ", " + sel.end); yes maybe.
It is even easier if you use
http://plugins.jquery.com/project/a-tools
Good luck :)
edit: note that the msot cursor is often referred to as a “carriage”, just FYI;)