Keyboard events and contenteditable.
This fiddle was created to examine which events are generated before the text node is change and which are generated after.
I've had a few surprises with non-US keyboards and ibus.
HTML
<p contenteditable="true">
toto
</p>
JavaScript
/* Simple test to see which event is issued *before* a keyboard event changes a text node and which event is issued *after*.
Lessons learned:
* Keyup is issued after the node is modified.
* The other events are issued before.
* When typing precomposed letters (like when switching to the French keyboard and typing é), only the keypress event has a which value which makes any sense. (Keydown and keyup both see a value of 0.)
* When typing letters composed by ibus (like when entering the letter ā), only the keyup event is fired and has the value 65 (uppercase A).
*/
$('p').on('keydown keyup keypress', handle);
function handle(ev) {
var selection = getSelection();
var focus_node = selection.focusNode;
focus_node.normalize();
// Note that you must have your javascript console turned on to see the results.
console.log("event type:", ev.type);
console.log("which:", ev.which);
console.log("keyCode:", ev.keyCode);
console.log("charCode:", ev.charCode);
console.log("node value:", focus_node.nodeValue);
}
function getSelection() {
var sel;
if (window.getSelection)
sel = window.getSelection();
else if (document.getSelection)
sel = document.getSelection();
else
throw new Error("bork");
return sel;
}