As already discussed, the input
event for contenteditable
elements is not support on IE.
see compatibility chart.
But, we already know an event that does work on IE, and that's the keydown
event listener, but obviously it fires on every key, and not only keys which add/remove characters, so there should be a validation mechanism in place.
Also it is known that the keydown
event doesn't update the value of the element
(its textContent
) when fired, but after a delay, so a settimeout
should be used.
Last, we must sniff the browser, to only fallback to this method for IE:
polyfill:
// https://stackoverflow.com/a/37199444/104380
var msie = window.document.documentMode;
var elm = document.querySelector('div');
///////////////////////
// bind the events
if( msie )
elm.addEventListener("keydown", onKeydown);
else
elm.addEventListener("input", onKeydown);
///////////////////////
// events' callbacks
function onKeydown(e){
// keydown requires a delay for the input's value to actually change
setTimeout(function(){
onInput.call(this, e)
})
}
function onInput(e){
var value = e.target.textContent.trim();
// vaildate an actual character was pressed and not a non-character key
if( e.target.lastValue == value ) return;
// save the value on the input state object
e.target.lastValue = value;
console.log(value);
}
[contenteditable]{
border:1px solid silver;
padding:5px;
}
<div contenteditable></div>