views:

525

answers:

3

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
hmm...it doesn't work(FF), i get just 0 no matter what
kmunky
+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
i tried your function in FF and it doesn't work, wach time no matter what i get 0
kmunky
+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