Search code examples
javascripthtmldom-eventscontenteditablekeyboard-events

How can I programmatically simulate typing in a contenteditable HTML element?


I need to simulate the interaction of a user typing into a contenteditable HTML element programmatically.

I cannot use things such as HTMLElement.onkeypress() or HTMLElement.fire().

I cannot modify the actual code or content of the element using element.innerHTML or element.textContent, I need a way to simulate it.


Solution

  • You could use Document.execCommand() with the insertText command, which will also fire input events automatically:

    const editor = document.getElementById('editor');
    
    editor.oninput = (e) => console.log('Input');
    
    setTimeout(() => {
      editor.focus();
      
      document.execCommand('insertText', false, 'Inserted text...\n\n');
    }, 1000);
    body {
      display: flex;
      flex-direction: column;
      font-family: monospace;
    }
    
    #editor {
      box-shadow: 0 0 32px 0 rgba(0, 0, 0, .125);
      border-radius: 2px;
      min-height: 64px;
      padding: 16px;
      outline: none;
    }
    <div id="editor" contenteditable="true"></div>

    However, note that's currently obsolete and even before it was inconsistent across different browser (same as contenteditable):

    Obsolete

    This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.