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!
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();
}
}