hi there, how can i get cursor position in a textarea using jQuery? thanks
+1
A:
Not jQuery, but just Javascript...
var position = window.getSelection().getRangeAt(0).startOffset;
dacracot
2009-12-11 23:15:31
hmm...it doesn't work(FF), i get just 0 no matter what
kmunky
2009-12-14 12:43:08
+4
A:
function caretPos(el)
{
var pos = 0;
// IE Support
if (document.selection)
{
el.focus ();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart ('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
// Firefox support
else if (el.selectionStart || el.selectionStart == '0')
pos = el.selectionStart;
return pos;
}
BojanG
2009-12-11 23:36:10
i tried your function in FF and it doesn't work, wach time no matter what i get 0
kmunky
2009-12-14 13:33:33
+1
A:
Modified BojanG's solution to work with jQuery. Tested in Chrome, FF, and IE.
new function($) {
$.fn.getCursorPosition = function() {
var pos = 0;
var el = $(this).get(0);
// IE Support
if (document.selection) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
// Firefox support
else if (el.selectionStart || el.selectionStart == '0')
pos = el.selectionStart;
return pos;
}
} (jQuery);
Basically, to use it on a text box, do the following:
$("#myTextBoxSelector").getCursorPosition();
Ryan
2009-12-15 20:02:08