views:

80

answers:

2

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?

A: 

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.

lam3r4370
That's not what the second piece of code is doing.
Tim Down
But this is what I thought and wanted to do the second piece.
lam3r4370
OK. In which case, all you need for that is `document.getElementById('txtarr').value.length`
Tim Down
I did it in jQuery way ,but thanks!
lam3r4370
Yes, I was merely demonstrating how easy it is without jQuery for the case of a single element.
Tim Down
+1  A: 

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: http://stackoverflow.com/questions/3053542/how-to-get-the-start-and-end-points-of-selection-in-text-area/3053640#3053640

Tim Down