I augment text while it is written, like e.g. syntax highlighting via spans around kewords, in a contentediatable field.
I have the common problem of the cursor jumping towards the begin of the contenteditable. I tried the solution by Nico Burns on Set cursor position on contentEditable <div> it worked in the example but not for my code, possibly because I change the DOM inside the contenteditable itself.
full code at: http://pastie.org/2060277
output.addEventListener('keyup',augmentInput,false);
output.addEventListener('keydown',saveCursorPos,false);
output.addEventListener('mousedown',saveCursorPos,false);
output.addEventListener('keyup',restoreCursorPos,false);
function saveCursorPos(e){
//var selection = window.getSelection();
savedRange = window.getSelection().getRangeAt(0);
console.log("save "+e.type,savedRange);
}
function restoreCursorPos(e){
document.getElementById("output").focus();
if (savedRange != null) {
var s = window.getSelection();
if (s.rangeCount > 0){
s.removeAllRanges();
}
s.addRange(savedRange);
console.log("range !=0 "+e.type, savedRange);
}
else {
window.getSelection().addRange(savedRange);
console.log("range ==0 "+e.type, savedRange);
}
}
striking:
- That the Range is saved like it should on mouse click (in reference to the innermost element the cursor is in, with correct offset) but not if it is saved on keydown (than in reference to the contenteditable itself, startOffset always 0, not matter where the cursor was)
- If I prevent the cursor to be saved on keydown and just use the mouseup to save the range it is resored like if it was never saved properly or it changed: reference to the contenteditable itself, startOffset always 0. So I wonder if the range object is changing e.g. reflecting changes in the DOM?