I'm pretty certain that this is a "security" thing, as I've run into the same thing when trying to simulate key presses before.
Q: How can I type programatically then?
A: Getting/setting selectionStart, selectionEnd, etc, as well as using these in combination with String methods like slice
to insert characters. (See HTMLTextAreaElement reference)
Q: Why would you still use this kind of event then?
A: All of the event listeners will work as if it was a real key event.
Reduced functionality for arrows/home/end can be achieved thusly DEMO
function homeKey(elm) {
elm.selectionEnd =
elm.selectionStart =
elm.value.lastIndexOf(
'\n',
elm.selectionEnd - 1
) + 1;
}
function endKey(elm) {
var pos = elm.selectionEnd,
i = elm.value.indexOf('\n', pos);
if (i === -1) i = elm.value.length;
elm.selectionStart = elm.selectionEnd = i;
}
function arrowLeft(elm) {
elm.selectionStart = elm.selectionEnd -= 1;
}
function arrowRight(elm) {
elm.selectionStart = elm.selectionEnd += 1;
}
function arrowDown(elm) {
var pos = elm.selectionEnd,
prevLine = elm.value.lastIndexOf('\n', pos),
nextLine = elm.value.indexOf('\n', pos + 1);
if (nextLine === -1) return;
pos = pos - prevLine;
elm.selectionStart = elm.selectionEnd = nextLine + pos;
}
function arrowUp(elm) {
var pos = elm.selectionEnd,
prevLine = elm.value.lastIndexOf('\n', pos),
TwoBLine = elm.value.lastIndexOf('\n', prevLine - 1);
if (prevLine === -1) return;
pos = pos - prevLine;
elm.selectionStart = elm.selectionEnd = TwoBLine + pos;
}
Q: Where does it go wrong?
A: If lines are long enough to be wrapped, it will treat them as if unwrapped.