The following code is the best I’ve been able to find for an editable HTML textarea for a WYSIWYG editor. It can save and restore the caret position. It works on FF3.5+, IE8, but does not work on Opera 11, Safari 5, or Chrome 10. Any ideas why? I’m just trying to find some code that works on FF3+, opera 10+, safari 5, chrome 8+, and IE7+.
function doGetCaretPosition(ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
// Firefox support
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
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();
}
}
cpos=doGetCaretPosition(document.getElementById('yourtextareaID'));
setCaretPosition(document.getElementById('yourtextareaID'),cpos);