Search code examples
javascriptjquerykeypresscontenteditablesimulate

Simulate keypress on contenteditable element with jQuery


How to simulate keypress inside of a contenteditable div Programatically?

I want to remove characters programatically with a jQuery script without any human typing.

I would like to delete some characters from the end of the span tag with simulating a Backspace keypress inside of the contenteditable div.

<div class="editor" contenteditable="true">
    <span>This is a span!!</span>
</div>

So the result would be something like this:

This is a span

I wouldn't like to rewrite the text. I need to simulate backspace keypress. Tested with this code, but nothing happened.

$(document).ready(function(){ // after the website loaded
    // I want to trigger a keypress (backspace key) 
    // inside of the contenteditable div Programatically
    $('.editor').trigger(jQuery.Event('keypress', { keycode: 8 }));
});

Can you help me?


Solution

  • I used some part of code that was mentioned in the comments: SO answer - Yuri

    Here is the part that triggers the keydown event

    $(document).ready(function(){ // after the website loaded
    
        // I want to trigger a keypress (backspace key)
        // inside of the contenteditable div Programatically
        var e = jQuery.Event("keydown");
        e.which = 8; // backspace key
        $(".editor").trigger(e);
    });
    

    After that, I created a handler to .editor element

    $(".editor").keydown(function(e) {
       if (e.originalEvent === undefined) {
          console.log('triggered programmatically');
       } else {
          console.log('triggered by the user');
       }
    
       console.log("Key pressed:" + e.which);
    
       if(e.which == 8) {
           // do your stuff
       }
    });
    

    I also, put a validator to check if the event was trigged by user or programmatically.