I\'d like to track the movement of the caret/cursor in a contenteditable. I\'m not sure what\'s the best way to do this, though.
I\'m currently listening for click, key
It's not an easy task for the reasons you said. I came up with some kludge like this:
var caretInterval, caretOffset;
document.addEventListener("keydown", function(e) {
if (!e.target.contentEditable || caretInterval) return;
if (e.keyCode !== 37 && e.keyCode !== 39) // Left and right
return;
var sel = getSelection();
caretInterval = setInterval(function() {
if (sel.type === "Caret") caretOffset = sel.baseOffset;
}, 50);
});
document.addEventListener("keyup", function(e) {
if (e.keyCode !== 37 && e.keyCode !== 39) // Left and right
return;
clearInterval(caretInterval);
caretInverval = null;
var sel = getSelection();
if (sel.type === "Caret") caretOffset = sel.baseOffset;
});
There could be a small problem if someone tries to press left and right at the same time. For ctrl-X and ctrl-V, you should catch the cut and paste event, and that's actually another pain in the bollocks.
In the end, I decided it wasn't worth the effort for my purposes. Maybe you have different needs.