2

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?

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
pepe024
  • 25
  • 6
  • I don't understand what behaviour you want to develop. Do you want to remove character by character when the user presses the key backspace with a span tag? – Daniel 976034 Feb 07 '18 at 11:44
  • No, I want to remove characters Programatically with a jQuery script without any human typing. – pepe024 Feb 07 '18 at 11:55
  • What condition or event would initiate said function? – zer00ne Feb 07 '18 at 12:03
  • The page load event, after the website loaded. – pepe024 Feb 07 '18 at 12:10
  • I would go with `str.substring(0, str.length - 1)`. Otherwise, check this [SO answer](https://stackoverflow.com/a/832121/1151408) – Yuri Feb 07 '18 at 12:11
  • @Yuri Thanks for your answer. I already tested the solution that you linked. The main problem is that the contenteditable div is not working that way. Is it even possible to trigger a contenteditable element? – pepe024 Feb 07 '18 at 12:19
  • I have checked the selected answer and seems it is working and showing output in the console, but there is no affect on the 'editor' did you find an correct answer for your question? – Reza Amya Mar 03 '20 at 03:14

1 Answers1

1

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.