Consider the following sample code, based on this answer.
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script>
$(this).ready( function() {
$("#foobar").keydown(function(e) {
if (e.keyCode != KeyEvent.DOM_VK_UP) {
console.log("Foo Bar");
var f = jQuery.Event("keydown");
f.which = KeyEvent.DOM_VK_UP;
f.keyCode = KeyEvent.DOM_VK_UP;
$("#foobar").trigger(f);
e.preventDefault();
e.stopImmediatePropagation();
}
else {
console.log("Hello World");
}
});
})
</script>
<div id="foobar" contenteditable="true">
Foo Bar
<br>
Bar Bar
</div>
</body>
The output of this example is that the following is printed to the console very time a key is pressed. However, only when the real Up
is pressed, does the cursor move up.
Foo Bar
Hello World
This implies that the trigger worked, but the cursor does not move up.
How can I make the cursor behave exactly as if the user had pressed the Up
key on his keyboard when any key is pressed, not just a real Up
?
I also tried the following way of triggering, which was also unsuccessful, despite printing true
for success.
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent ("keypress", true, true, window,
0, 0, 0, 0, KeyEvent.DOM_VK_UP, KeyEvent.DOM_VK_UP);
var success = document.getElementById("foobar").dispatchEvent(evt)
console.log(success)