javascript - Is it possible to programmatically detect the caret position within a <input type=text> element? -
assuming regular <input type=text>
text-box data in it.
is possible detect (via javascript) position of text-coursor inside text-box?
i able detect arrow left or arrow right keydown event - how detect cursor location?
why need this:
i have dynamic text-box here: http://vidasp.net/tinydemos/dynamic-textbox.html
works great, there 2 scenarios fix:
- when cursor @ beginning of text-box , user presses backspace
- when cursor @ end of text-box , user presses delete
(in both cases, text-box must contain data effect observable.)
i've done quite lot of work on this. following works in major browsers (including ie 6) text <input>
s , <textarea>
s , work in situations, including when there leading , trailing spaces (which many solutions, including a-tools, fall down). there's background code in question: ie's document.selection.createrange doesn't include leading or trailing blank lines
you can following part of jquery input/textarea selection plug-in i've written yet undocumented: 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 working textrange lives in input textinputrange = el.createtextrange(); textinputrange.movetobookmark(range.getbookmark()); // check if start , end of selection @ end // of input, since movestart/moveend doesn't return want // in 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);
Comments
Post a Comment