简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM