0

I have these two codes -

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);

And

var element = document.getElementById('txtarr');
if( document.selection ){
      // The current selection
    var range = document.selection.createRange();
      // We'll use this as a 'dummy'
    var stored_range = range.duplicate();
      // Select all text
    stored_range.moveToElementText( element );
      // Now move 'dummy' end point to end point of original range
    stored_range.setEndPoint( 'EndToEnd', range );
      // Now we can calculate start and end points
    element.selectionStart = stored_range.text.length - range.text.length;
    element.selectionEnd = element.selectionStart + range.text.length;
}

The first one is for getting the cursor position in a textarea and the second one is for determining the end of a textarea ,but they give the same result? Where's the mistake?

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 2
    Please describe a real-world case with that the textarea contains, what the expected result is, what the actual result is, and where you use the functions using what event(s). – Pekka Jul 03 '10 at 11:59
  • I use the functions on pressing backspace. The second function returns number ,which shows where the textarea ends.The first function should return where the caret position is in the textarea.But the two functions return the same result (E.g. the first returns 37 and the second returns 37 ,which ,as number is the end of the textarea). –  Jul 03 '10 at 12:13

2 Answers2

0

I fix it.It's very simple :) . I just replace the second code(for determining the end of the textarea) with:$("#txtarr").val().length(jQuery).#txtarr is the id of mine textarea.

0

Both pieces of code are doing the same thing in slightly different ways. Each is attempting to get the position of the caret or selection in a textarea (or text input), although the first only gets the start position of the selection while the second gets both the start and end positions.

Both have flaky inferences: the first assumes a browser featuring document.selection will support TextRange, while the second makes the same inference plus another that assumes a browser without support for document.selection will have support for selectionStart and selectionEnd properties of textareas. Neither will correctly handle line breaks in IE. For code that does that, see my answer here: How to get the start and end points of selection in text area?

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536