keyup event on contenteditable div

Viewed 7468

I'm attempting to format the text in an contenteditable div after Enter is pressed. The problem is that no keyups are being registered from any key, so this is making it impossible. Other events, such as 'click' does work, and if I change the element to 'document' (document.addEventListener()...) this will make it work too, but this is an extreme solution. Is there a simple solution?

window.addEventListener('load', function() {
    var editbox = document.getElementById("editable")
    editbox.addEventListener('keyup', function(e) {
        alert("this should appear");
    });
});
<main contenteditable="true">
    <div class="box" id="editable">
        text
    </div>
</main>

4 Answers

There is another solution. You can just detect an inputType.

const divInput = document.getElementById('divInput');
const textarea = document.getElementById('inputTypePreview');

divInput.addEventListener('input', (event) => {
  const t = event.inputType;
  textarea.innerHTML = `${t} \n`;
  if (t === 'insertParagraph' || t === 'insertLineBreak') 
    textarea.innerHTML = 'Enter detected \n';
 });
#inputTypePreview {
  margin: 1em 0 0;
}
#divInput, #inputTypePreview {
  border: 1px solid #b1b0b0;
  border-radius: 3px;
  width: 100%;
  resize: none;
}
<div id="divInput" contentEditable="true"></div>
<textarea id="inputTypePreview" disabled></textarea>

Related