2

i've got a function which allows me to set a caret inside a textarea.

here it is

function setCaretPosition(ctrl, pos) {
    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

What i'm trying to do is as soon as the page loads i want to set the caret at a particular position after focus() like so.

$("#sometextarea").focus();
setCaretPosition(document.getElementById('sometextarea'),last_update_caret);

however it does not work, i've tried a lot of different methods such as blur() instead of focus() then trying to set it at a certain position (it works after 5-6 tries for some reason but thats not desired as i want it to do it when the page loads automatically).

I want it to scroll down aswell if the text is lengthy!

Example

Answer

var caret = 88;
  
$(function() {
  setCaretPosition(document.getElementById('sometextarea'), caret);
  $textarea = $("#sometextarea");
  var cursorPosition = $textarea.prop("selectionStart");
  $textarea.scrollTop(cursorPosition);
});



function setCaretPosition(ctrl, pos) {

  if (ctrl.setSelectionRange) {
    ctrl.focus();
    ctrl.setSelectionRange(pos, pos);
  } else if (ctrl.createTextRange) {
    var range = ctrl.createTextRange();
    range.collapse(true);
    range.moveEnd('character', pos);
    range.moveStart('character', pos);
    range.select();
  }
}
Community
  • 1
  • 1
xenogfx
  • 23
  • 4
  • It could (I think...) be an issue with focus not running/rendering immediately because it interacts with the DOM. Try setting the caret position in a setTimeout call. – Marie Feb 18 '16 at 21:37
  • alright let me try this also. – xenogfx Feb 18 '16 at 21:38

1 Answers1

0

I think this was working for me, as long as I understand the intended purpose. All I did was add the shorthand for document ready to make sure everything was loaded before attempting the function:

$(function(){

var  last_update_caret = 3;

$("#sometextarea").focus();

setCaretPosition(document.getElementById('sometextarea'),last_update_caret)
;


function setCaretPosition(ctrl, pos) {

    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}
  });
TylerT
  • 69
  • 6
  • does it scroll down if the text is lengthy? check my example – xenogfx Feb 18 '16 at 21:43
  • for the additional question i would look into keypress after the focus is set. http://stackoverflow.com/questions/29899364/how-do-you-scroll-to-the-position-of-the-cursor-in-a-textarea – TylerT Feb 18 '16 at 21:50